#!/system/xbin/bash
#
# Sapphire ScriptyBox Script
# The mother-load of all scripts O.O
#
# This script is designed to act similarly to busybox in how it
# can have symlinks of it made and whatnot to run the commands.
#
# Copyright (C) 2010 Austen Dicken (cvpcs)
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

# name of this script
SCRIPT_NAME=scriptybox

# etc directories
SYSTEM_ETC=/system/etc
SCRIPT_ETC="${SYSTEM_ETC}/scriptybox"

# location of file downloads
FILES_URL="$(getprop ro.cvpcs.scriptybox.files_url)"

# first assume we're using a symbolic link
CMD=$(basename $0)
ARG=$@

# we override these if using the gem interface
STDOUT="/proc/self/fd/1"
STDERR="/proc/self/fd/2"
GEM_STDOUT="/cache/sb.out"
GEM_STDERR="/cache/sb.err"

# ensure we are getting an argument
if busybox [ ! -z "${ARG}" ] ; then
	# if we are calling the script directly, shift the args
	if busybox [ "$(busybox basename $0)" == "${SCRIPT_NAME}" ] ; then
		# oh noes! direct scripting! time to shift and reset
		CMD=$1;	shift 1
		ARG=$@
	fi
fi

# check for scriptybox gem interface
if busybox [ "$(getprop gem.sb.exec)" = "1" ] ; then
	# clear our set bit
	setprop "gem.sb.exec" "0"

	# set command and clean/sanatize it
	CMD="$(busybox echo $(getprop gem.sb.arg0) | busybox sed -r 's/[^a-zA-Z0-9_-]//g')"
	setprop "gem.sb.arg0" ""

	# create our argument list
	ARG="$(busybox echo $(getprop gem.sb.arg1) | busybox sed -r 's/[^a-zA-Z0-9_-]//g')"
	setprop "gem.sb.arg1" ""

	i=2
	while [ ! -z "$(getprop gem.sb.arg${i})" ] ; do
		ARG="${ARG} $(busybox echo $(getprop gem.sb.arg${i}) | busybox sed -r 's/[^a-zA-Z0-9_-]//g')"
		setprop "gem.sb.arg${i}" ""

		i=$(busybox expr ${i} + 1)
	done

	# at this point we should have a sanatized command string, now redirect output
	STDOUT="${GEM_STDOUT}"
	STDERR="${GEM_STDERR}"
fi

# declare our internal commands
function __adblock () {
###############################################################################
# function name: __adblock
# parameters: $1 - (on|off): determine if ad blocking turns on or off
# returns: void
# description:
#     uses the phone's hostfile to block ads
#
	hostfile_local="${SCRIPT_ETC}/hosts.local"
	hostfile_adblock="${SCRIPT_ETC}/hosts.adblock"

	if busybox [ $# == 0 ] ; then
		__adblock_help
	else
		case $1 in
			on)
				__sysrw > /dev/null
				busybox echo -n "Enabling ad blocking ... " > "${STDOUT}"
				busybox cat "${hostfile_local}" > /system/etc/hosts
				busybox cat "${hostfile_adblock}" >> /system/etc/hosts
				busybox echo "done" > "${STDOUT}"
				__sysro > /dev/null
			;;
			off)
				__sysrw > /dev/null
				busybox echo -n "Disabling ad blocking ... " > "${STDOUT}"
				busybox cat "${hostfile_local}" > /system/etc/hosts
				busybox echo "done" > "${STDOUT}"
				__sysro > /dev/null
			;;
			*)
				__adblock_help
			;;
		esac
	fi
}

function __adblock_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    adblock [on|off]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Turns ad blocking for the system on or off" > "${STDOUT}"
}

function __camsounds () {
###############################################################################
# function name: __camsounds
# parameters: $1 - (on|off): determine if camera sound turns on or off
# returns: void
# description:
#     rename camera sound files to disable the video record and camera click
#     sounds
#
	sound_clk="/system/media/audio/ui/camera_click.ogg"
	sound_rec="/system/media/audio/ui/VideoRecord.ogg"

	if busybox [ $# == 0 ] ; then
		__camsounds_help
	else
		case $1 in
			on)
				__sysrw > /dev/null
				busybox echo -n "Enabling camera audio ... " > "${STDOUT}"
				if busybox [ -e "${sound_clk}.bak" ] ; then busybox mv "${sound_clk}.bak" "${sound_clk}"; fi
				if busybox [ -e "${sound_rec}.bak" ] ; then busybox mv "${sound_rec}.bak" "${sound_rec}"; fi
				busybox echo "done" > "${STDOUT}"
				__sysro > /dev/null
				;;
			off)
				__sysrw > /dev/null
				busybox echo -n "Disabling camera audio ... " > "${STDOUT}"
				if busybox [ -e "${sound_clk}" ] ; then busybox mv "${sound_clk}" "${sound_clk}.bak"; fi
				if busybox [ -e "${sound_rec}" ] ; then busybox mv "${sound_rec}" "${sound_rec}.bak"; fi
				busybox echo "done" > "${STDOUT}"
				__sysro > /dev/null
				;;
			*)
				__camsounds_help
				;;
		esac
	fi
}

function __camsounds_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    camsounds [on|off]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Turns the camera sounds (shutter and video cam) on or off" > "${STDOUT}"
}

function __compcache () {
###############################################################################
# function name: __compcache
# parameters: $1 - (on|off): determine if compcache turns on or off
# returns: void
# description:
#     turns on compcache ramzswap module and enables it (or shuts of and
#     disables it)
#
	if busybox [ $# == 0 ] ; then
		__compcache_help
	else
                rzswap_mod=ramzswap
                rzswap_size=20480
                rzswap_file=/dev/block/ramzswap0
                rzctrl=$(busybox which rzscontrol 2>/dev/null)

		if busybox [ -z "${rzctrl}" ] ; then
		        busybox echo "FATAL ERROR: Could not find rzscontrol applicaiton" > "${STDERR}"
		        return
		fi

		# sanity check 2: does our module exist?
		if busybox [ -z "$(busybox find /system/lib/modules -name *${rzswap_mod}* 2>/dev/null)" ] ; then
		        # no module, maybe the ram device just exists?

		        if busybox [ ! -b "${rzswap_file}" ] ; then
		                busybox echo "FATAL ERROR: System does not support compcache" > "${STDERR}"
		                return
		        fi
		fi

		case $1 in
			on)
		               if busybox [ -z "$(busybox lsmod | busybox grep ${rzswap_mod})" ] ; then
		                        busybox echo -n "Loading ramzswap module ... " > "${STDOUT}"

		                        if ! busybox modprobe "${rzswap_mod}" "disksize_kb=${rzswap_size}" ; then
		                                busybox echo "FAIL" > "${STDERR}"
		                                return
		                        fi

					busybox echo "done" > "${STDOUT}"
		                fi

		                if busybox [ -z "$(busybox grep ${rzswap_file} /proc/swaps)" ] ; then
					busybox echo -n "Enabling swap ... " > "${STDOUT}"
		                        busybox swapon "${rzswap_file}"
					busybox echo "done" > "${STDOUT}"
		                fi

				busybox echo "Compcache has been enabled" > "${STDOUT}"
				;;
			off)
        		        if busybox [ ! -z "$(busybox grep ${rzswap_file} /proc/swaps)" ] ; then
		                        busybox echo -n "Disabling swap ... " > "${STDOUT}"
		                        busybox swapoff "${rzswap_file}"
					busybox echo "done" > "${STDOUT}"

					busybox echo -n "Resetting ramzswap ... " > "${STDOUT}"
		                        "${rzctrl}" "${rzswap_file}" --reset
					busybox echo "done" > "${STDOUT}"
		                fi

		                if busybox [ ! -z "$(busybox lsmod | busybox grep ${rzswap_mod})" ] ; then
		                        busybox echo -n "Unloading ramzswap module ... " > "${STDOUT}"
		                        busybox modprobe -r "${rzswap_mod}"
					busybox echo "done" > "${STDOUT}"
		                fi

				busybox echo "Compcache has been disabled" > "${STDOUT}"
				;;
			stats)
				if busybox [ -b "${rzswap_file}" ] ; then
					"${rzctrl}" "${rzswap_file}" --stats > "${STDOUT}"
				else
					busybox echo "Compcache does not appear to be enabled" > "${STDOUT}"
				fi
				;;
			*)
				__compcache_help
				;;
		esac
	fi
}

function __compcache_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    compcache [on|off|stats]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Turns compcache (in-RAM swap) on or off" > "${STDOUT}"
}

function __cpuinfo () {
###############################################################################
# function name: __cpuinfo
# parameters: void
# returns: void
# description:
#    displays the information about the processor
#
	if busybox [ $# -gt 0 ] ; then
		__cpuinfo_help
	else
		if busybox [ -e /proc/cpuinfo ] ; then
			busybox cat /proc/cpuinfo > "${STDOUT}"
		else
			busybox echo "Cpuinfo not supported by kernel" > "${STDOUT}"
		fi
	fi
}

function __cpuinfo_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    cpuinfo" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Displays all of the CPU information for the system" > "${STDOUT}"
}

function __cwiid () {
###############################################################################
# function name: __cwiid
# parameters: $1 - (on|off|status): determine if compcache turns on or off or
#                                   displays a status
# returns: void
# description:
#     turns on (or off) cwiid wiimote connectivity, or displays the status
#     of the daemon
#
	if busybox [ $# == 0 ] ; then
		__cwiid_help
	else
		cwiictrl="$(busybox which wminput 2>/dev/null)"
		cwiiconf="$(getprop persist.gem.cwiid.conf)"

		if busybox [ -z "${cwiictrl}" ] ; then
		        busybox echo "FATAL ERROR: Could not find wminput applicaiton" > "${STDERR}"
		        return
		fi

		if busybox [ -z "${cwiiconf}" ] ; then
			cwiiconf="buttons"
		fi

		case $1 in
			on)
				if busybox [ ! -z "$(busybox pgrep wminput 2>/dev/null)" ] ; then
					busybox echo "CWiiD daemon is already running." > "${STDOUT}"
				else
					busybox echo -n "Starting CWiiD daemon ... " > "${STDOUT}"

					"${cwiictrl}" -c "${cwiiconf}" -d 2>/dev/null &

					busybox sleep 2s

					if busybox [ ! -z "$(busybox pgrep wminput 2>/dev/null)" ] ; then
						busybox echo "done" > "${STDOUT}"
					else
						busybox echo "ERROR" > "${STDERR}"
					fi
				fi
				;;
			off)
				busybox echo -n "Killing CWiiD Daemon ... " > "${STDOUT}"

				busybox killall -s INT wminput 2>/dev/null

				# wait and see if it dies
				i=0
				while busybox [ ! -z "$(busybox pgrep wminput 2>/dev/null)" ] ; do
					busybox sleep 1s

					if busybox [ ${i} -lt 5 ] ; then
						i=$(busybox expr ${i} + 1)
					else
						break
					fi
				done

				# if it STILL hasn't died, we kill it
				i=0
				while busybox [ ! -z "$(busybox pgrep wminput 2>/dev/null)" ] ; do
					busybox killall wminput 2>/dev/null
					busybox sleep 1s

					if busybox [ ${i} -lt 5 ] ; then
						i=$(busybox expr ${i} + 1)
					else
						break
					fi
				done

				if busybox [ -z "$(busybox pgrep wminput 2>/dev/null)" ] ; then
					setprop "gem.cwiid.status" "stopped"
					busybox echo "done" > "${STDOUT}"
				else
					setprop "gem.cwiid.status" "error"
					busybox echo "ERROR" > "${STDERR}"
				fi
				;;
			status)
				if busybox [ -z "$(busybox pgrep wminput 2>/dev/null)" ] ; then
					busybox echo "CWiiD daemon is currently not running." > "${STDOUT}"
				else
					busybox echo "CWiiD daemon is currently running." > "${STDOUT}"
				fi
				busybox echo "It's state is: [$(getprop gem.cwiid.status)]" > "${STDOUT}"
				;;
			*)
				__cwiid_help
				;;
		esac
	fi
}

function __cwiid_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    cwiid [on|off|status]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Turns CWiiD (WiiMote Connectivity) on or off, or displays status" > "${STDOUT}"
}

function __freemem () {
###############################################################################
# function name: __freemem
# parameters: $1 - (50mb|75mb|100mb|default): how much ram to keep free
#             $2 - (i_understand_how_stupid_this_is_and_choose_to_use_it_anyway): verification of use
# returns: void
# description:
#     set up the memfree task killer to leave a certain amount of ram free
#
	if busybox [ $# == 0 ] ; then
		__freemem_help
	else
		if busybox [ "$2" == "i_understand_and_choose_to_use_it_anyway" ] ; then
			case $1 in
				50mb)
					# 10mb,15mb,25mb,30mb,40mb,50mb
					__freemem_helper 2560 3840 6400 7680 10240 12800
					;;
				75mb)
					# 10mb,15mb,25mb,40mb,50mb,75mb
					__freemem_helper 2560 3840 6400 10240 12800 19200
					;;
				100mb)
					# 10mb,15mb,25mb,50mb,70mb,100mb
					__freemem_helper 2560 3840 6400 12800 12800 25600
					;;
				default)
					# 6mb,8mb,16mb,20mb,22mb,24mb (default)
					__freemem_helper 1536 2048 4096 5120 5632 6144
					;;
				*)
					__freemem_help
					;;
			esac
		else
			__freemem_warning
		fi
	fi
}

function __freemem_warning () {
	busybox echo "!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Freemem is a script that tells the native task killer for" > "${STDOUT}"
	busybox echo "Android to keep large blocks of memory available at all" > "${STDOUT}"
	busybox echo "times.  This is poor in practice as unused memory is" > "${STDOUT}"
	busybox echo "wasted memory.  It is best to use the default settings" > "${STDOUT}"
	busybox echo "to allow the system to make the most out of the memory" > "${STDOUT}"
	busybox echo "it has available." > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "If you wish to ignore this warning, you can still run" > "${STDOUT}"
	busybox echo "this command by adding the following to the end of the" > "${STDOUT}"
	busybox echo "command:" > "${STDOUT}"
	busybox echo "  i_understand_and_choose_to_use_it_anyway" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Example:" > "${STDOUT}"
	busybox echo "  freemem 50mb i_understand_and_choose_to_use_it_anyway" > "${STDOUT}"
}

function __freemem_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    freemem [50mb|75mb|100mb|default]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Configures the system to enusre that at least a given" > "${STDOUT}"
	busybox echo "amount of RAM is always available" > "${STDOUT}"
}

function __freemem_helper () {
###############################################################################
# function name: __freemem_helper
# parameters: $1,$2,$3,$4,$5,$6 - ([0-9]+): memory values to kill at
# returns: void
# description:
#     helper function to push memkill values to the low memory killer
#
	if busybox [ $# == 6 ] ; then
		busybox echo -n "Setting memkiller to keep $(busybox expr $6 \* 4 / 1024)mb of RAM free ... " > "${STDOUT}"
		busybox echo "$1,$2,$3,$4,$5,$6" > /sys/module/lowmemorykiller/parameters/minfree
		busybox echo "done" > "${STDOUT}"
		busybox echo "" > "${STDOUT}"
		busybox echo "WARNING: Increasing auto-task killing may have adverse effects" > "${STDOUT}"
		busybox echo "         on the system.  If you experience unexpected issues," > "${STDOUT}"
		busybox echo "         try reducing the amount of memory kept free." > "${STDOUT}"
	else
		busybox echo "Unable to set memkiller ... " > "${STDERR}"
	fi
}

function __halt () {
###############################################################################
# function name: __halt
# parameters: void
# returns: void
# description:
#     shuts down the phone to a power-off state (no reboot)
#
	if busybox [ $# -gt 0 ] ; then
		__halt_help
	else
		busybox echo "Powering down ... " > "${STDOUT}"
		reboot -p
	fi
}

function __halt_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    halt" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Powers off the phone" > "${STDOUT}"
}

function __meminfo () {
###############################################################################
# function name: __meminfo
# parameters: void
# returns: void
# description:
#     prints out info about the memory on the system
#
	if busybox [ $# -gt 0 ] ; then
		__meminfo_help
	else
		if busybox [ -e /proc/meminfo ] ; then
			busybox cat /proc/meminfo > "${STDOUT}"
		else
			busybox echo "Meminfo not supported by kernel" > "${STDERR}"
		fi
	fi
}

function __meminfo_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    meminfo" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Displays all of the memory information for the system" > "${STDOUT}"
}

function __mtdinfo () {
###############################################################################
# function name: __mtdinfo
# parameters: void
# returns: void
# description:
#     prints out info about the memory partitions of the system
#
	if busybox [ $# -gt 0 ] ; then
		__mtdinfo_help
	else
		if busybox [ -e /proc/mtd ] ; then
			busybox cat /proc/mtd > "${STDOUT}"
		else
			busybox echo "Mtdinfo not supported by kernel" > "${STDERR}"
		fi
	fi
}

function __mtdinfo_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    mtdinfo" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Displays all of the internal partitions for the system" > "${STDOUT}"
}

function __rmapk () {
###############################################################################
# function name: __rmapk
# parameters: $1 - {name}: name of the apk to remove
# returns: void
# description:
#     removes an apk from the system app folder
#
	if busybox [ $# == 0 ] ; then
		__rmapk_help
	else
		case $1 in
			alarm)
				__rmapk_helper \
					"Alarm Clock" \
					"/system/app/AlarmClock.apk"
				;;
			browser)
				__rmapk_helper \
					"Browser" \
					"/system/app/Browser.apk"
				;;
			calc)
				__rmapk_helper \
					"Calculator" \
					"/system/app/Calculator.apk"
				;;
			corpcal)
				__rmapk_helper \
					"Corporate Calendar" \
					"/system/app/CorpCal.apk"
				;;
			deskclock)
				__rmapk_helper \
					"Desk Clock" \
					"/system/app/DeskClock.apk"
				;;
			devtools)
				__rmapk_helper \
					"Dev Tools" \
					"/system/app/Development.apk"
				;;
			email)
				__rmapk_helper \
					"Email" \
					"/system/app/Email.apk"
				;;
			genie)
				__rmapk_helper \
					"News and Weather" \
					"/system/app/GenieWidget.apk"
				;;
			lwps)
				__rmapk_helper \
					"Live Wallpapers" \
					"/system/app/LiveWallpapers.apk" \
					"/system/app/MagicSmokeWallpapers.apk" \
					"/system/app/VisualizationWallpapers.apk"
				;;
			mms)
				__rmapk_helper \
					"MMS" \
					"/system/app/Mms.apk"
				;;
			music)
				__rmapk_helper \
					"Music" \
					"/system/app/Music.apk"
				;;
			qoffice)
				__rmapk_helper \
					"QuickOffice" \
					"/system/app/SholesQuickOffice.apk"
				;;
			spare)
				__rmapk_helper \
					"Spare Parts" \
					"/system/app/SpareParts.apk"
				;;
			speech)
				__rmapk_helper \
					"Speech Recorder" \
					"/system/app/SpeechRecorder.apk"
				;;
			tips)
				__rmapk_helper \
					"Tips" \
					"/system/app/Protips.apk"
				;;
			*)
				__rmapk_help
				;;
		esac
	fi
}

function __rmapk_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "     rmapk [alarm|browser|calc|corpcal|deskclock|" > "${STDOUT}"
	busybox echo "            devtools|email|genie|lwps|mms|music|" > "${STDOUT}"
	busybox echo "            qoffice|spare|speech|tips]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Removes applications that may be unwanted on some" > "${STDOUT}"
	busybox echo "systems.  The Applications are:" > "${STDOUT}"
	busybox echo "     alarm - Alarm Clock" > "${STDOUT}"
	busybox echo "     browser - Stock browser" > "${STDOUT}"
	busybox echo "     calc - Stock calculator" > "${STDOUT}"
	busybox echo "     corpcal - Corporate Calendar" > "${STDOUT}"
	busybox echo "     deskclock - Desk Clock" > "${STDOUT}"
	busybox echo "     devtools - Development Tools" > "${STDOUT}"
	busybox echo "     email - Stock email" > "${STDOUT}"
	busybox echo "     genie - News and Weather" > "${STDOUT}"
	busybox echo "     lwps - Live Wallpapers" > "${STDOUT}"
	busybox echo "     mms - Stock MMS" > "${STDOUT}"
	busybox echo "     music - Music" > "${STDOUT}"
	busybox echo "     qoffice - QuickOffice" > "${STDOUT}"
	busybox echo "     spare - Spare Parts" > "${STDOUT}"
	busybox echo "     speech - Speech Recorder" > "${STDOUT}"
	busybox echo "     tips - Tips" > "${STDOUT}"
}

function __rmapk_helper () {
###############################################################################
# function name: __rmapk_helper
# parameters: $1 - {name}: name of the app being removed (used for display)
#             $2[,..] - {file}: files to be removed
# returns: void
# description:
#     helper function that performs the removal of the specified app
#
	app_name=$1; shift 1
	app_files=$@

	if busybox [ ! -z "${app_name}" ] ; then
		busybox echo "Removing application: ${app_name}" > "${STDOUT}"

		__sysrw > /dev/null

		for apk in ${app_files}; do
			busybox echo -n "  Removing file: ${apk} ... " > "${STDOUT}"

			if busybox [ -e "${apk}" ] ; then
				# i am basenaming this to make sure nothing bad happens
				busybox rm "/system/app/$(busybox basename ${apk})"
				busybox echo "done" > "${STDOUT}"
			else
				busybox echo "already removed" > "${STDOUT}"
			fi
		done

		__sysro > /dev/null
	fi
}

function __swapinfo () {
###############################################################################
# function name: __swapinfo
# parameters: void
# returns: void
# description:
#     displays info about any swap space on the device
#
	if busybox [ $# -gt 0 ] ; then
		__swapinfo_help
	else
                if busybox [ -e /proc/swaps ] ; then
			busybox cat /proc/swaps > "${STDOUT}"
		else
			busybox echo "Swapinfo not supported by kernel" > "${STDERR}"
		fi
	fi
}

function __swapinfo_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    swapinfo" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Displays all of the swap information for a system" > "${STDOUT}"
}

function __switchapk () {
###############################################################################
# function name: __switchapk
# parameters: $1 - {name}: name of the apk to switch
# returns: void
# description:
#     downloads and swaps apks from the sapphire host server
#
	switchapk_files_url="${FILES_URL}/switchapk"

	if busybox [ $# != 2 ] ; then
		__switchapk_help
	else
		case $1 in
			clock)
				case $2 in
					alarm)
						__switchapk_helper \
							"Clock" "2.2 Alarm Clock" \
							"AlarmClock.apk" "AlarmClock.apk" \
							"DeskClock.apk"
						;;
					desk)
						__switchapk_helper \
							"Clock" "2.2 Desk Clock" \
							"DeskClock.apk" "DeskClock.apk" \
							"AlarmClock.apk"
						;;
					*)
						busybox echo "Did not understand [$@]" > "${STDOUT}"
						;;
				esac
				;;
			music)
				case $2 in
					milestone)
						__switchapk_helper \
							"Music" "Milestone Music" \
							"MilestoneMusic.apk" "Music.apk" \
							"Music.apk"
						;;
					stock)
						__switchapk_helper \
							"Music" "2.2 Stock Music" \
							"Music.apk" "Music.apk" \
							"Music.apk"
						;;
					*)
						busybox echo "Did not understand [$@]" > "${STDOUT}"
						;;
				esac
				;;
			*)
				__switchapk_help
				;;
		esac
	fi
}

function __switchapk_help {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    switchapk [application selection]" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Switches default applications for the following:" > "${STDOUT}"
	busybox echo "    clock [alarm|desk] - either the AlarmClock or DeskClock app" > "${STDOUT}"
	busybox echo "    music [milestone|stock] - either the Milestone or stock 2.2" > "${STDOUT}"
        busybox echo "             Music app" > "${STDOUT}"
}

function __switchapk_helper () {
###############################################################################
# function name: __switchapk_helper
# parameters: $1 - {old_app_name}: name of the apk being replaced
#             $2 - {new_app_name}: name of the new apk
#             $3 - {new_app_file}: name of the new file
#             $4 - {copy_to_file}: file name to copy to
#             $@ - {delete_files}: files to delete (old files)
# returns: 0: success
#          1: failure
# description:
#     downloads and swaps apks from the sapphire host server
#
	if busybox [ $# -gt 4 ] ; then
		old_app_name="$1"
		new_app_name="$2"
		new_app_file="$3"
		copy_to_file="$4"; shift 4
		delete_files="$@"

		busybox echo "Replacing ${old_app_name} with ${new_app_name} ..." > "${STDOUT}"

		busybox echo "  Downloading required files:" > "${STDOUT}"
		busybox echo -n "    ${new_app_file} ... " > "${STDOUT}"
		busybox wget -q -O "/cache/${new_app_file}" "${switchapk_files_url}/${new_app_file}"
		if busybox [ -e "/cache/${new_app_file}" ] ; then
			busybox echo "done" > "${STDOUT}"

			busybox echo -n "    ${new_app_file}.chksum ... " > "${STDOUT}"
			busybox wget -q -O "/cache/${new_app_file}.chksum" "${switchapk_files_url}/${new_app_file}.chksum"
			if busybox [ -e "/cache/${new_app_file}.chksum" ] ; then
				busybox echo "done" > "${STDOUT}"

				busybox echo "  Verifying download:" > "${STDOUT}"

				chksum_passed="1"

				for i in md5 sha1 sha256 sha512; do
					busybox echo -n "    Verifying ${i} checksum ... " > "${STDOUT}"
					if busybox echo "$(busybox grep "${i}" "/cache/${new_app_file}.chksum" | busybox awk '{print $2 "  " $3}')" | busybox "${i}sum" -c -s ; then
						busybox echo "pass" > "${STDOUT}"
					else
						busybox echo "FAIL" > "${STDERR}"
						chksum_passed="0"
					fi
				done

				if busybox [ "$chksum_passed" -eq "1" ] ; then
					busybox echo -n "  Switching apks ... "; > "${STDOUT}"

					__sysrw > /dev/null

					for old_app_file in ${delete_files}; do
						if busybox [ -e "/system/app/${old_app_file}" ] ; then
							busybox rm "/system/app/${old_app_file}"
						fi
					done

					if busybox [ -e "/system/app/${copy_to_file}" ] ; then
						busybox rm "/system/app/${copy_to_file}"
					fi

					busybox cp "/cache/${new_app_file}" "/system/app/${copy_to_file}"
					busybox chown 0.0 "/system/app/${copy_to_file}"
					busybox chmod 644 "/system/app/${copy_to_file}"

					__sysro > /dev/null

					busybox echo "done" > "${STDOUT}"
				else
					busybox echo "  There was an error verifying your downloads" > "${STDERR}"
					busybox echo "  Switch ABORTED" > "${STDERR}"
				fi

				busybox echo -n "  Cleaning up ... " > "${STDOUT}"
				busybox rm "/cache/${new_app_file}"
				busybox rm "/cache/${new_app_file}.chksum"
				busybox echo "done" > "${STDOUT}"
			else
				busybox echo "FAILED" > "${STDERR}"
			fi
		else
			busybox echo "FAILED" > "${STDERR}"
		fi
	fi

}

function __sysro () {
###############################################################################
# function name: __sysro
# parameters: void
# returns: void
# description:
#     remounts the /system partition read-only
#
	if busybox [ $# -gt 0 ] ; then
		__sysro_help
	else
		busybox echo -n "Remounting /system read-only ... " > "${STDOUT}"

		# i'm throwing the sleeps in there in hopes that it will fix
		# the problems i'm having :S
		sleep 2s

		sync
		busybox mount -o remount,ro /system

		busybox echo "done" > "${STDOUT}"
	fi
}

function __sysro_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    sysro" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Mounts the /system partition read-only" > "${STDOUT}"
}

function __sysrw () {
###############################################################################
# function name: __sysrw
# parameters: void
# returns: void
# description:
#     remounts the /system partition read-write
#
	if busybox [ $# -gt 0 ] ; then
		__sysrw_help
	else
		busybox echo -n "Remounting /system read-write ... " > "${STDOUT}"
		busybox mount -o remount,rw /system
		busybox echo "done" > "${STDOUT}"
	fi
}

function __sysrw_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    sysrw" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Mounts the /system partition read/write" > "${STDOUT}"
}

function __zipalign_apks () {
###############################################################################
# function name: __zipalign_apks
# parameters: void
# returns: void
# description:
#     cycles through all of the apks on your system and zipaligns them if they
#     are not already
#
	if busybox [ $# -gt 0 ] ; then
		__zipalign_apks_help
	else
		# find our apks
		sys_apks=$(busybox find /system -name '*.apk')
		dat_apks=$(busybox find /data -name '*.apk')

		# zipalign apks
		__sysrw > /dev/null

		for apk in ${sys_apks} ${dat_apks}; do
			apk_name="$(busybox basename ${apk})"
			apk_cache="/cache/${apk_name}"

			# check if we are already zipaligned
			if ! zipalign -c 4 ${apk} ; then
				busybox echo -n "${apk} - ZipAligning ... " > "${STDOUT}"

				# nope, time to zipalign
				zipalign -f 4 "${apk}" "${apk_cache}"

				# check if file exists
				if busybox [ -e "${apk_cache}" ] ; then
					busybox cp -f "${apk_cache}" "${apk}"
					busybox rm "${apk_cache}"

					busybox echo "done"; > "${STDOUT}"
				else
					busybox echo "ERROR"; > "${STDERR}"
				fi
			else
				busybox echo "${apk} - Already ZipAligned. Skipping" > "${STDOUT}"
			fi
		done

		__sysro > /dev/null
	fi
}

function __zipalign_apks_help () {
	busybox echo "Usage:" > "${STDOUT}"
	busybox echo "    zipalign_apks" > "${STDOUT}"
	busybox echo "" > "${STDOUT}"
	busybox echo "Automagickally zipaligns all of the APK files found on your system" > "${STDOUT}"
	busybox echo "NOTE: THIS WILL ZIPALIGN ANY APK UNDER /system OR /data" > "${STDOUT}"
}

function __scriptybox_help () {
	case $1 in
		adblock)
			__adblock_help
			;;
		camsounds)
			__camsounds_help
			;;
                compcache)
                        __compcache_help
                        ;;
		cpuinfo)
			__cpuinfo_help
			;;
		cwiid)
			__cwiid_help
			;;
		freemem)
			__freemem_help
			;;
		halt)
			__halt_help
			;;
		meminfo)
			__meminfo_help
			;;
		mtdinfo)
			__mtdinfo_help
			;;
		rmapk)
			__rmapk_help
			;;
		swapinfo)
			__swapinfo_help
			;;
		switchapk)
			__switchapk_help
			;;
		sysro)
			__sysro_help
			;;
		sysrw)
			__sysrw_help
			;;
		zipalign_apks)
			__zipalign_apks_help
			;;
		*)
			busybox echo "Please type a valid command to view its help information" > "${STDERR}"
			;;
	esac
}

case ${CMD} in
	adblock) # done
		__adblock ${ARG}
		;;
	camsounds) # done
		__camsounds ${ARG}
		;;
        compcache)
                __compcache ${ARG}
                ;;
	cpuinfo) # done
		__cpuinfo ${ARG}
		;;
	cwiid) # done
		__cwiid ${ARG}
		;;
	freemem) # done
		__freemem ${ARG}
		;;
	halt) # done
		__halt ${ARG}
		;;
	meminfo) # done
		__meminfo ${ARG}
		;;
	mtdinfo) # done
		__mtdinfo ${ARG}
		;;
	rmapk) # done
		__rmapk ${ARG}
		;;
	swapinfo) # done
		__swapinfo ${ARG}
		;;
	switchapk)
		__switchapk ${ARG}
		;;
	sysro) # done
		__sysro ${ARG}
		;;
	sysrw) # done
		__sysrw ${ARG}
		;;
	zipalign_apks) # done
		__zipalign_apks ${ARG}
		;;
	help)
		__scriptybox_help
		;;
	*)
		busybox echo "Available commands:" > "${STDOUT}"
		busybox echo "" > "${STDOUT}"
		busybox echo "     adblock [on|off]" > "${STDOUT}"
		busybox echo "     camsounds [on|off]" > "${STDOUT}"
		busybox echo "     cpuinfo" > "${STDOUT}"
		busybox echo "     compcache [on|off|stats]" > "${STDOUT}"
		busybox echo "     cwiid [on|off|status]" > "${STDOUT}"
		busybox echo "     freemem [50mb|75mb|100mb|default]" > "${STDOUT}"
		busybox echo "     halt" > "${STDOUT}"
		busybox echo "     meminfo" > "${STDOUT}"
		busybox echo "     mtdinfo" > "${STDOUT}"
		busybox echo "     rmapk [alarm|browser|calc|carhome|corpcal|" > "${STDOUT}"
		busybox echo "            deskclock|devtools|email|genie|lwps|mms|" > "${STDOUT}"
		busybox echo "            mp3|music|qoffice|search|spare|speech|tips|" > "${STDOUT}"
		busybox echo "            vvm]" # dock > "${STDOUT}"
		busybox echo "     swapinfo" > "${STDOUT}"
		busybox echo "     switchapk [clock|music]" > "${STDOUT}"
		busybox echo "     sysro" > "${STDOUT}"
		busybox echo "     sysrw" > "${STDOUT}"
		busybox echo "     zipalign_apks" > "${STDOUT}"
		busybox echo "" > "${STDOUT}"
		busybox echo "You can type \"scriptybox help [command]\" to see" > "${STDOUT}"
		busybox echo "help related to that command" > "${STDOUT}"
		;;
esac

busybox echo "" > "${STDOUT}"
busybox echo "(Android $(getprop ro.build.version.release) / $(getprop ro.modversion) [$(getprop ro.build.id)] by $(getprop ro.rommanager.developerid))" > "${STDOUT}"
