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

if grep -q " /data/cache " /proc/mounts; then
    busybox mkdir /data/cache;
    busybox chown 1000:2001 /data/cache;
    busybox chmod 770 /data/cache;
    if [ -d /cache/dalvik-cache ] && [ ! -d /data/cache/dalvik-cache ]; then
      busybox cp -a /cache/dalvik-cache /data/cache/;
      busybox rm -f /cache/dalvik-cache/*;
      busybox rmdir /cache/dalvik-cache;
    fi
    busybox mount -obind /data/cache /cache;
fi

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;