#!/system/bin/sh

# DarkyROM 2011
# Much faster zipalign.

# Changelog:
# 1.2 (17/1/11) Added /data/zipalign.db file for faster apk check (ninpo,Bo$s)
# 1.1 (12/1/09) Switched to zipalign -c 4 to check the apk instead of MD5 (oknowton)
# 1.0 (11/30/09) Original

# make sure /system is writable
mount -o rw,remount /system

TMPDIR=/mnt/var
TMPAPK=$TMPDIR/.temp.apk
ZIPALIGNBIN=/system/xbin/zipalign
ZIPALIGNDB=/cache/zipalign.db
LOG_FILE=$TMPDIR/zipalign.log
APKDIRS="/data/app /system/app"

mkdir -p $TMPDIR
rm -f $LOG_FILE
touch $ZIPALIGNDB

echo "Starting Automatic ZipAlign $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE

for DIR in $APKDIRS ; do
  for APK in $(find $DIR -name '*.apk'); do
    CRC=$(stat -c ""%x"" $APK | cut -d. -f1)' '$APK
    if [ "$CRC" -ot $ZIPALIGNDB ] && [ $(grep "$CRC" $ZIPALIGNDB|wc -l) -gt 0 ] ; then
      echo "Already checked: $APK" | tee -a $LOG_FILE
    else
      ZIPCHECK=`$ZIPALIGNBIN -c -v 4 $APK | grep FAILED | wc -l`
      if [ $ZIPCHECK == "1" ]; then
        echo "Now aligning: $APK" | tee -a $LOG_FILE
        $ZIPALIGNBIN -v -f 4 $APK $TMPAPK | tee -a $LOG_FILE
        [ -f $TMPAPK ] && cp -f $TMPAPK $APK && chmod 0644 $APK
        CRC=$(stat -c ""%x"" $APK | cut -d. -f1)' '$APK
        rm -f $TMPAPK
      else
        echo "Already aligned: $APK" | tee -a $LOG_FILE
      fi
      grep "$CRC" $ZIPALIGNDB > /dev/null || echo "$CRC" >> $ZIPALIGNDB
    fi
  done
done

touch $ZIPALIGNDB
echo "Automatic ZipAlign finished at $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE
