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

LOG_FILE=/data/zipalign.log
    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
	     	apkfile=$(basename "$apk")
		dest="/cache/$apkfile"
		echo "ZipAligning $dest" | tee -a $LOG_FILE;
		zipalign -f 4 "$apk" "$dest";
                rc="$?";
		if [ "$rc" -eq 0 ]; then
			if [ -e "$dest" ]; then
				cp -f -p "$dest" "$apk"  | tee -a $LOG_FILE;
				rm -f "$dest";
			else
				echo "ZipAligning $apkfile Failed (no output file)"  | tee -a $LOG_FILE;
			fi;
		else
			[ -f "$dest" ] && rm -f "$dest";
			echo "ZipAligning $apkfile Failed (rc: $rc)"  | 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;