#!/bin/bash

  
  TOOLDIR=tools/android_img_repack_tools
  CONTEXTS=../../$TOOLDIR/file_contexts
  
  clear
  
  if [ `ls STOCK | grep recovery.img` ]
  
    then
  
    tools/mkbootimg_tools/mkboot STOCK/recovery.img PROJECT/recovery
    
    CONTEXTS=../../PROJECT/recovery/ramdisk/file_contexts
    
    else
      
      CONTEXTS=../../$TOOLDIR/file_contexts
      
      fi
  
  
  echo -e
  echo -en "\E[32;1m Building new image EXT4FS_SE... \E[32;0m"
  echo -e
  echo -e
  echo -en "\033[1m Input building image <name> *****.img: \033[0m"
  tput sgr0
  
  read INPUT
  
  echo -e
  echo -en "\033[1m  Input <partition size> b/Mb: \033[0m"
  tput sgr0
  
  read SIZE
  
  echo -e
  echo -en "\033[1m  Input partition <mount point> /*****: \033[0m"
  tput sgr0
  
  read MP
  
  echo -e
  echo -en "\033[1m  Input partition <hiader size> 28/32 bytes: \033[0m"
  tput sgr0
  
  read HSIZE
  
  
  cd $TOOLDIR
  
  if [ `uname | grep Linux` ]
  
      then
      
      sudo ./mkuserimg.sh -s ../../PROJECT/$INPUT.mnt ../../PROJECT/$INPUT ext4 $MP $SIZE $CONTEXTS
      
          elif [ `uname | grep CYGWIN` ]
          
          then
          
          ./mkuserimg.sh -s ../../PROJECT/$INPUT.mnt ../../PROJECT/$INPUT ext4 $MP $SIZE $CONTEXTS
  fi
  
  cd ../..
  
  if [ `echo $HSIZE | grep 32` ]
  
      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
  fi
  
  if [ `ls PROJECT | grep recovery` ]
  
      then
      
      rm -r PROJECT/recovery
  fi
  
  if [ `uname | grep Linux` ]
      then
      
      sudo chown 1000.1000  PROJECT/$INPUT
  fi
  
  echo -e
  echo -en "\033[1m Finished \033[0m"
  echo -e
  tput sgr0
  echo -e
  echo "Press Enter to continue"
  read enterKey
