############################################################################
#
# Copyright (c) 2012 - dsixda (dislam@rocketmail.com)
#
# Android Kitchen is 100% free.  This script file is intended for personal
# and/or educational use only.  It may not be duplicated for monetary
# benefit or any other purpose without the permission of the developer.
#
############################################################################

#
# This script extracts the contents of the boot.img from the Working folder
#
# It has one optional parameter:
#
# $1 = if set to 'no_clear' then it won't clear at start
#

if [ "$1" == "" ]
then
  clear
fi

scripts/prompt_remove_boot_extracted

if [ ! -d BOOT-EXTRACTED ]
then

  if [ -d WORKING_* ]
  then
    echo
    echo Working folder found
  else
    echo
    echo Working folder not found, you will need to create one!
    exit 0
  fi

  cd WORKING_*

  if [ -e boot.img ]
  then

    cd ..
    scripts/check_bootimg_header
    scripts/check_kernel_offset
    res=$?

    if [ "$res" == "0" ]
    then
      kernel_file=extract-kernel.pl
      ramdisk_file=extract-ramdisk.pl
    else
      exit 0
    fi

    echo Making folder 'BOOT-EXTRACTED' ...
    cd WORKING_*
    mkdir ../BOOT-EXTRACTED
    cp boot.img ../BOOT-EXTRACTED/
    
    cd ..
    cp tools/extract_boot_files/$kernel_file BOOT-EXTRACTED/extract-kernel.pl
    cp tools/extract_boot_files/$ramdisk_file BOOT-EXTRACTED/extract-ramdisk.pl
    cd BOOT-EXTRACTED

    echo
    echo Extracting kernel ...
    ./extract-kernel.pl boot.img 2>/dev/null
   
    if [ ! -e zImage ]
    then
      echo "Error: No zImage found!"
    else
      test_z=`od -A n -j 1 -N 4 zImage | sed 's/ //g'`
      if [ "$test_z" == "" ]
      then
        echo "Error: zImage is empty!"
      fi
    fi

    echo Extracting ramdisk ... 
    ./extract-ramdisk.pl boot.img 2>/dev/null

    if [ ! -d boot.img-ramdisk ]
    then
      echo "Error: No ramdisk folder found!"
    fi

    rm boot.img
    rm extract-*.pl
    cd ..
    echo

  else

    if [ -e boot/initrd.gz ] && [ -e boot/zImage ]
    then
      cd ..
      scripts/ensure_nand_extracted $1

    else
      echo "Error: boot.img not found!"
      echo
      cd ..
      exit 0
    fi
  fi      

fi

