#!/system/bin/sh
#Defrags database files

log -p i -t sqlite-optimize "Starting sqlite-optimize"

LOG_FILE=/data/S50-vacuum-databases.log

# do nothing if less than 7 days
find $LOG_FILE -type f -mtime +7 -delete

if ! test -f $LOG_FILE; then

	if [ -e $LOG_FILE ]; then
		rm $LOG_FILE;
	fi;
    	
	echo "Starting Sqlite Vacuum $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE;

	for i in \
	`find /data -iname "*.db"`
	do \
		sqlite3 $i 'REINDEX;';
		sqlite3 $i 'VACUUM;'; 
		log -p i -t sqlite-optimize "Vacuum & Reindex $i";
		echo Vacuum \& Reindex $i  | tee -a $LOG_FILE;
	done;

#
# the SD FAT has not been mounted yet
#
	mount /dev/block/mmcblk0p1 /mnt/sdcard
	for i in \
	`find /mnt/sdcard -iname "*.db"`
	do \
		sqlite3 $i 'VACUUM;'; 
		sqlite3 $i 'REINDEX;';
		log -p i -t sqlite-optimize "Vacuum & Reindex $i";
		echo Vacuum \& Reindex $i  | tee -a $LOG_FILE;
	done
#
# Unmount the SD FAT. Otherwise it will fail when Android will take possess of it later.
#
	umount /mnt/sdcard

	echo "Sqlite Vacuum finished at $( date +"%m-%d-%Y %H:%M:%S" )" | tee -a $LOG_FILE;
fi

log -p i -t sqlite-optimize "sqlite-optimize ended"
