#!/system/bin/sh
# Automatic ZipAlign For Fly-On Mod by slaid480
# ZipAlign files in /data that have not been previously
# Thanks to mcbyte_it 



LOG_FILE=/data/zipalign.log
#Interval between ZipAlign runs, in seconds, 172800=48h 
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;
