#!/bin/bash
  
  TOOLDIR=tools/android_img_repack_tools
  
  clear
  
  echo -e
  echo -en "\E[32;1m Mounting RAW image... \E[32;0m"
  echo -e
  echo -e
  echo -en "\033[1m Choose ext4 image for edit \033[0m"
  echo -e
  echo -e
  
  find STOCK/ -maxdepth 1 -regex '.*\(.img\|.ext4\)' -type f -exec ls {} \;
  
  echo -e
  echo -en "\033[1m Input image <name>: \033[0m"
  tput sgr0
  read INPUT
  
  mkdir PROJECT/$INPUT.mnt
  
  #UTF8 may slow down grep, switch to C
  
  export LANG=C

      #Test for the ext4 magic and convert from sparse to raw
  
  if [ `head -c 2 STOCK/$INPUT | grep -aobP -m1 '\x3A\xFF'` ]
  
    then
  
    $TOOLDIR/simg2img STOCK/$INPUT PROJECT/$INPUT.raw
    
      else
 
      #Test for the extra header and calculate its position and convert from sparse to raw
          
          magic=`grep -aobP -m1 '\x3A\xFF' STOCK/$INPUT | head -1 | cut -d":" -f1`
  
          offset=$(($magic))
  
          echo -en "\033[1m  Rename original $INPUT \033[0m"
  
          mv -v STOCK/$INPUT STOCK/$INPUT.orig
  
          echo -e
          echo -e
  
          dd if=STOCK/$INPUT.orig of=STOCK/$INPUT ibs=$offset skip=1
  
          dd if=STOCK/$INPUT.orig of=STOCK/IVEH_$INPUT ibs=$offset count=1
  
          $TOOLDIR/simg2img STOCK/$INPUT PROJECT/$INPUT.raw
          
  fi
  
  #Mount or extract ext4 raw img
  
  if [ `uname | grep Linux` ]
  
  then
  
     sudo mount -t ext4 -o loop PROJECT/$INPUT.raw PROJECT/$INPUT.mnt
     
  elif [ `uname | grep CYGWIN` ]
  
  then
  
     tools/ImgExtractor_V1_1/ImgExtractor.exe PROJECT/$INPUT.raw PROJECT/$INPUT.mnt -i
     
  fi
  
  echo
  echo -en "\033[1m Finished \033[0m"
  echo -e
  tput sgr0
  echo
  echo "Press Enter to continue"
  read enterKey
