#!/bin/bash
  
  
  TOOLDIR=tools/android_img_repack_tools
  
  clear
  
  echo -e
  echo -en "\E[32;1m Convertig RAW to SPARSE 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
  

  $TOOLDIR/ext2simg -v PROJECT/$INPUT.raw PROJECT/$INPUT
  
  echo -e
  
  #UTF8 may slow down grep, switch to C
  
  export LANG=C

  #Look for the chunk header and calculate its position
  
  if [ `head -c 9 STOCK/$INPUT | grep -aobP -m1 '\x20'` ]
  
    then
    
      mv -v PROJECT/$INPUT PROJECT/$INPUT.tmp
      
      $TOOLDIR/sgs4ext4fs --bloat PROJECT/$INPUT.tmp PROJECT/$INPUT
      
      rm -f PROJECT/$INPUT.tmp
      
      chmod 0644 PROJECT/$INPUT
      
  elif
  
      [ `head -c 9 STOCK/$INPUT | grep -aobP -m1 '\x1C'` ]
      
    then
    
      chmod 0644 PROJECT/$INPUT
      
  fi

  if [ `uname | grep Linux` ]
  
    then
    
      sudo chown 1000.1000  PROJECT/$INPUT
      
  fi
  
  echo
  echo -en "\033[1m Finished \033[0m"
  echo -e
  tput sgr0
  echo
  echo "Press Enter to continue"
  read enterKey
