#!/system/bin/sh

FLY=/data/local/sqlite_optimize.log

#Interval between Optimize SQlite runs, in seconds, 108000=30 hours
RUN_EVERY=108000

# Get the last modify date of the Log file, if the file does not exist, set value to 0
if [ -e $FLY ]; then
    LASTRUN=`stat -t $FLY | 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 $FLY ]; then
        rm $FLY;
    fi;
	fi;
        
    echo "SQLite database VACUUM and REINDEX started at $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $FLY;

    for i in `busybox find /d* -iname "*.db"`; do
        /system/xbin/sqlite3 $i 'VACUUM;';
        resVac=$?
        if [ $resVac == 0 ]; then
            resVac="SUCCESS";
        else
            resVac="ERRCODE-$resVac";
        fi;
        
        /system/xbin/sqlite3 $i 'REINDEX;';
        resIndex=$?
        if [ $resIndex == 0 ]; then
            resIndex="SUCCESS";
        else
            resIndex="ERRCODE-$resIndex";
        fi;
        echo "Database $i:  VACUUM=$resVac  REINDEX=$resIndex" | tee -a $FLY;
    done
      
    echo "SQLite database VACUUM and REINDEX finished at $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $FLY;
fi;