#!/system/xbin/bash
: '
 ============ Copyright (C) 2010 Jared Rummler (JRummy16) ============
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 =====================================================================
'

SUGGESTIONS_DATABASE=/data/data/com.android.vending/databases/suggestions.db

if busybox [ -z "$( busybox which sqlite3 )" ]; then
	echo "Missing sqlite3. Exiting..."
	exit 1
elif busybox [ ! -e $SUGGESTIONS_DATABASE ]; then
	echo "Suggestions database not found. Are you sure you have market history?"
	exit 1
fi

while true; do
	
	unset HISTORY
	OLD_IFS="$IFS"
	IFS=$'\n'
	HISTORY=(` sqlite3 $SUGGESTIONS_DATABASE "SELECT query FROM suggestions" `);
	IFS="$OLD_IFS"

	length=${#HISTORY[*]}
	if busybox [ $length -eq 0 ]; then
		echo "You have no market history."
		exit 0
	fi

	echo "=========================================="
	N=1
	for ((i=0; i < $length; i++)); do
		echo " $N) ${HISTORY[$i]}"
		let N++
	done
	echo " $N) Clear all history"
	EXIT_MENU=$(($N+1))
	echo " $EXIT_MENU) Exit this menu"
	echo "=========================================="
	echo " Enter a number to remove it from history"
	echo "------------------------------------------"
	echo -n " Please enter a number: "

	read choice
	case $choice in
		''|*[!0-9]*) 
			echo "Error: you went crazy and entered something wrong."
			exit 1
		;;
		$N)
			for ((i=0; i < $length; i++)); do
				sqlite3 $SUGGESTIONS_DATABASE "DELETE FROM suggestions WHERE query='${HISTORY[$i]}'"
				echo "Removed ${HISTORY[$i]}"
			done
			echo
			echo "All market history cleared!"
			echo
			exit 0
		;;
		$EXIT_MENU)
			exit 0
		;;
		*)
			INDEX=$(($choice-1))
			sqlite3 $SUGGESTIONS_DATABASE "DELETE FROM suggestions WHERE query='${HISTORY[$INDEX]}'"
			echo "Removed ${HISTORY[$INDEX]}"
		;;
	esac

done