#!/system/bin/sh

# be sure init.rc post-fs-data completed
until [ `getprop vold.post_fs_data_done`. = 1. ]; do sleep 1; done

# run script only when battery charged enough
capacity=$(cat /sys/class/power_supply/battery/capacity)
if [ "$capacity" -gt "15" ]; then

	echo "sqlite init script"

	if which sqlite3 >/dev/null; then
		echo "SQLite database VACUUM and REINDEX started at $(date +%Y%m%d-%H.%M.%S)"
		for i in `find /data/* -iname "*.db"`; do
			sqlite3 $i 'VACUUM;'
			resVac=$?
			if [ $resVac == 0 ]; then
				resVac="SUCCESS"
			else
				resVac="ERRCODE-$resVac"
			fi;

			sqlite3 $i 'REINDEX;'
			resIndex=$?
			if [ $resIndex == 0 ]; then
				resIndex="SUCCESS"
			else
				resIndex="ERRCODE-$resIndex"
			fi
			echo "Database $i:  VACUUM=$resVac  REINDEX=$resIndex"
		done

		echo "SQLite database VACUUM and REINDEX finished at $(date +%Y%m%d-%H.%M.%S)"
	else
		echo "sqlite3 not installed, stop"
	fi
fi
