#!/system/bin/sh
# Automatic ZipAlign by Wes Garner
# ZipAlign files in /data that have not been previously ZipAligned (using md5sum)

# Changelog:
# 1.0 (11/30/09) Original
# 1.1 (12/01/09) Switched to zipalign -c 4 to check the apk instead of MD5 (oknowton)
# 1.2 (06/01/13) Run the main script only once every N days (default 2 days) (mcbyte_it)

LOG_FILE=/data/zipalign.log
#Interval between ZipAlign runs, in seconds, 604800=1 week
RUN_EVERY=172800

# Get the last modify date of the Log file, if the file does not exist, set value to 0
if [ -e $LOG_FILE ]; then
    LASTRUN=`stat -t $LOG_FILE | awk '{print $14}'`
else
    LASTRUN=0
fi;

# Get current date in epoch format
CURRDATE=`date +%s`

# Check the interval
INTERVAL=$(expr $CURRDATE - $LASTRUN)

# If interval is more than the set one, then run the main script
if [ $INTERVAL -gt $RUN_EVERY ];
then
    if [ -e $LOG_FILE ]; then
        rm $LOG_FILE;
    fi;

    echo "Starting Automatic ZipAlign $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE;
    for apk in /data/app/*.apk ; do
        zipalign -c 4 $apk;
        ZIPCHECK=$?;
        if [ $ZIPCHECK -eq 1 ]; then
            echo ZipAligning $(basename $apk)  | tee -a $LOG_FILE;
            zipalign -f 4 $apk /cache/$(basename $apk);

            if [ -e /cache/$(basename $apk) ]; then
                cp -f -p /cache/$(basename $apk) $apk  | tee -a $LOG_FILE;
                rm /cache/$(basename $apk);
            else
                echo ZipAligning $(basename $apk) Failed  | tee -a $LOG_FILE;
            fi;
        else
            echo ZipAlign already completed on $apk  | tee -a $LOG_FILE;
        fi;
    done;
    echo "Automatic ZipAlign finished at $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE;
fi