#!/bin/sh

###################################
### TPDebrick v004 by jcsullins ###
###################################

check_pgms()
{
	local have_other=1
	local ok_install=0
	local lsb_rel
	local lsb_id
	local SP

	if ! `which perl >/dev/null 2>&1`;
	then
		echo "perl not found"
		echo "Aborting."
		exit 1
	fi

	lsb_rel=`lsb_release --short --release`
	lsb_id=`lsb_release --short --id`

	if [ -n "$lsb_rel" -a -n "${lsb_id}" -a "${lsb_id}" = "Ubuntu" ];
	then
		if [ "${lsb_rel}" = "11.04" -o "${lsb_rel}" = "11.10" -o "${lsb_rel}" = "12.04" ];
		then
			ok_install=1
		fi
	fi

	if ! `which dfu-util >/dev/null 2>&1`;
	then
		echo "dfu-util not installed"
		have_other=0
	fi
	if ! `which fastboot >/dev/null 2>&1`;
	then
		echo "fastboot not installed"
		have_other=0
	fi

	if [ $have_other -eq 1 ];
	then
		return;
	fi

	if [ $ok_install -eq 0 ];
	then
		echo "Aborted."
		exit 1
	fi

	if `which software-properties-kde >/dev/null 2>&1`;
	then
		SP=software-properties-kde
	else
		SP=software-properties-gtk
	fi

	echo "Installing dfu-util/fastboot ..."
	$SP --enable-component universe
	if [ $? -ne 0 ];
	then
		echo "Enable universe failed."
		echo "Aborted."
		exit 1
	fi
	add-apt-repository --yes ppa:nilarimogard/webupd8
	if [ $? -ne 0 ];
	then
		echo "add-apt-repository failed"
		echo "Aborted."
		exit 1
	fi
	apt-get update
	if [ $? -ne 0 ];
	then
		echo "apt-get update failed"
		echo "Aborted."
		exit 1
	fi
	apt-get --yes install dfu-util
	if [ $? -ne 0 ];
	then
		echo "install dfu-util failed"
		echo "Aborted."
		exit 1
	fi
	apt-get --yes install android-tools-fastboot
	if [ $? -ne 0 ];
	then
		echo "install fastboot failed"
		echo "Aborted."
		exit 1
	fi
}

check_files()
{
	local chk_list
	local need_files=0
	local doc_fn
	local doc_fn_wifi="webosdoctorp305hstnhwifi.jar"
	local doc_fn_3g="webosdoctorp305hstnhatt.jar"

	echo "checking doc files ..."
	chk_list="sbl1.mbn sbl2.mbn sbl3.mbn rpm.mbn tz.mbn"
	chk_list="${chk_list} emmc_appsboot.mbn"
	chk_list="${chk_list} bootie-topaz305.bin"
	chk_list="${chk_list} PmA6Updater"
	chk_list="${chk_list} a6_firmware.txt.00"

	for fn in $chk_list
	do
		if [ ! -r ${fn} ];
		then
			need_files=1
		fi
	done

	if [ $need_files -eq 0 ];
	then
		return
	fi

	if [ -r ../${doc_fn_wifi} ];
	then
		doc_fn=../${doc_fn_wifi}
	fi

	if [ -r ../${doc_fn_3g} ];
	then
		doc_fn=../${doc_fn_3g}
	fi

	if [ -z "${doc_fn}" ];
	then
		echo "could not find ../${doc_fn_wifi} or ../${doc_fn_3g}"
		echo "Aborted."
		exit 1
	fi

	echo "extracting doc files ..."

	unzip -p "${doc_fn}" resources/webOS.tar \
		| tar -xOf - ./nova-cust-image-topaz.rootfs.tar.gz \
		| tar -xzOf - ./boot/boot-genesis.tar.gz \
		| tar -xzf -
	if [ $? -ne 0 ];
	then
		echo "failed to extract core bootloaders"
		echo "Aborted."
		exit 1
	fi

	unzip -p "${doc_fn}" resources/webOS.tar | \
		tar -xOf - ./boot-topaz.bin \
		>bootie-topaz305-raw.bin
	if [ $? -ne 0 ];
	then
		echo "failed to extract boot.bin"
		echo "Aborted."
		exit 1
	fi
	PRINTF=`which printf 2>/dev/null`
	if [ $? -ne 0 ];
	then
		echo "printf not found."
		echo "Aborting."
		exit 1
	fi
	$PRINTF "\x1C\xC3\x01\x00\x00\x00\x80\x40" >bootie-topaz305.bin
	cat bootie-topaz305-raw.bin >>bootie-topaz305.bin
	$PRINTF "\x18\xDA\x06\x15" >>bootie-topaz305.bin

	unzip -p "${doc_fn}" resources/webOS.tar \
		| tar -xOf - ./nova-cust-image-topaz.rootfs.tar.gz \
		| tar -xzOf - ./usr/bin/PmA6Updater \
		>PmA6Updater
	if [ $? -ne 0 ];
	then
		echo "failed to extract PmA6Updater"
		echo "Aborted."
		exit 1
	fi
	chmod 755 PmA6Updater

	unzip -p "${doc_fn}" resources/webOS.tar | tar -xOf - ./nova-cust-image-topaz.rootfs.tar.gz | tar -xzOf - ./lib/firmware/a6_firmware.txt.00 >a6_firmware.txt.00
	if [ $? -ne 0 ];
	then
		echo "failed to extract a6_firmware.txt.00"
		echo "Aborted."
		exit 1
	fi
}


check_config_files()
{
local cfgf=$1

echo -n "Checking that config/files are valid... "

if [ \! -r ${cfgf} ];
then
	echo "FAILED"
	echo "Cannot read config file ${cfgf}"
	echo "Aborted."
	exit 1
fi

while read fname pos md5
do
	if [ "${fname}" = '#' ];
	then
		continue
	fi
	if [ \! -r "${fname}" ];
	then
		echo "FAILED"
		echo "Cannot read file ${fname}"
		echo "Aborted."
		exit 1
	fi
	if [ "${md5}" = "nocheck" ];
	then
		continue;
	fi
	CHK_MD5=`md5sum ${fname} | cut -d' ' -f1`
	if [ "${CHK_MD5}" !=  "${md5}" ];
	then
		echo "FAILED"
		echo "File ${fname} failed check."
		echo "Aborted."
		exit 1
	fi
done <${cfgf}
echo "OK"
}


load_files()
{
local cfgf=$1

while read fname pos md5
do
	if [ "${fname}" = '#' ];
	then
		continue;
	fi
	echo "Writing file ${fname} ... "
	addr=$(($pos * 512))
	perl qdload.pl --laddr ${addr} --lfile ${fname}
	if [ $? -ne 0 ];
	then
		echo "Cannot write file ${fname}"
		echo "Aborted."
		exit 1
	fi
done <${cfgf}
echo "Done writing files."
}

check_usbdevs()
{
	local tmout="$1"
	shift
	local dev_ids="$*"
	local check_flag=1

	while [ $check_flag -eq 1 ];
	do
		for dev_id in $dev_ids
		do
			dev_count=`lsusb | cut -d' ' -f6 | grep "^${dev_id}" | wc -l`
			if [ $dev_count -gt 0 ];
			then
				return 0
			fi
		done
		if [ $tmout -le 0 ];
		then
			check_flag=0
		else
			sleep 1
			tmout=$((tmout - 1))
		fi
	done
	return 1
}

get_usbdev_info()
{
	local devid=$1
	local field=$2
	local filter=$3

	if [ $field -eq 1 ];
	then
		lsusb -vv -d $devid |
			while read a b c
			do
				if [ "x${a}" = "x${filter}" ];
				then
					echo "${b}"
					return
				fi
			done
	else
		lsusb -vv -d $devid |
			while read a b c
			do
				if [ "x${a}" = "x${filter}" ];
				then
					echo "${c}"
					return
				fi
			done
	fi
}

check_qdlmode()
{
	local devid_qdl="05c6:9008"
	local imanfac1="`get_usbdev_info $devid_qdl 1 iManufacturer`"
	local imanfac2="`get_usbdev_info $devid_qdl 2 iManufacturer`"
	local iprod1="`get_usbdev_info $devid_qdl 1 iProduct`"
	local iprod2="`get_usbdev_info $devid_qdl 2 iProduct`"

	if [ -z "${imanfac1}" -o -z "${iprod1}" ];
	then
		return 1
	fi
	if [ -z "${imanfac2}" -o -z "${iprod2}" ];
	then
		return 1
	fi
	if [ "${imanfac1}" != "3" ];
	then
		return 1
	fi
	if [ "${imanfac2}" != "Qualcomm, Incorporated" ];
	then
		return 1
	fi
	if [ "${iprod1}" != "2" ];
	then
		return 1
	fi
	if [ "${iprod2}" != "Qualcomm CDMA Technologies MSM" ];
	then
		return 1
	fi
	return 0
}
	
check_qdlmode2()
{
	local devid_qdl="05c6:9008"
	local imanfac1="`get_usbdev_info $devid_qdl 1 iManufacturer`"
	local imanfac2="`get_usbdev_info $devid_qdl 2 iManufacturer`"
	local iprod1="`get_usbdev_info $devid_qdl 1 iProduct`"
	local iprod2="`get_usbdev_info $devid_qdl 2 iProduct`"

	if [ -z "${imanfac1}" -o -z "${iprod1}" ];
	then
		return 1
	fi
	if [ -z "${imanfac2}" -o -z "${iprod2}" ];
	then
		return 1
	fi
	if [ "${imanfac1}" != "1" ];
	then
		return 1
	fi
	if [ "${imanfac2}" != "Qualcomm CDMA Technologies MSM" ];
	then
		return 1
	fi
	if [ "${iprod1}" != "2" ];
	then
		return 1
	fi
	if [ "${iprod2}" != "QHSUSB_DLOAD" ];
	then
		return 1
	fi
	return 0
}
				

#####
##### MAIN
#####

devid_qdl="05c6:9008"


if [ $# -ne 1 ];
then
	echo "Usage: ${0} 16|32|64"
	exit 1
fi

if [ "$1" != "16" -a "$1" != "32" -a "$1" != "64" ];
then
	echo "Usage: ${0} 16|32|64"
	exit 1
fi

tptype="$1"

if [ `id -u` -ne 0 ];
then
	echo "Must run as superuser (i.e. sudo ...)"
	echo "Aborting"
	exit 1
fi

check_pgms
check_files

devid_qdl="05c6:9008"
devid_dfu="0830:8070"
devid_fastboot="18d1:d00d"
devid_netchip="0525:a4aa"

if `check_usbdevs 0 $devid_qdl`;
then
	if ! `check_qdlmode2`;
	then
		echo "Incorrect QDL mode found."
		echo "Please hold Power+Home+VolumeDown for 20-30 secs, then retry."
		echo "Aborted."
		exit 1
	fi
else
	echo "Connect Touchpad then hold Power+Home+VolumeDown for 30 seconds ..."
	if ! `check_usbdevs 120 $devid_qdl`
	then
		echo "QDL mode not found"
		echo "Aborting."
		exit 1
	else
		echo "Release buttons now"
		sleep 5
	fi
fi

perl qdload.pl --pfile emmcbld.bin
if [ $? -ne 0 ];
then
	echo "load of emmcbld.bin failed"
	echo "Aborting."
	exit 1
fi

sleep 3

echo "Checking QDL mode..."
if ! `check_qdlmode`;
then
	echo "QDL second stage mode not found"
	echo "Aborting"
	exit 1
fi

load_files tp${tptype}nobootie.cfg

echo "Reseting device..."
perl qdload.pl --lreset

echo "Waiting for fastboot mode..."
if ! `check_usbdevs 60 ${devid_fastboot}`
then
	echo "fastboot mode not found"
	echo "Aborted."
	exit 1
fi

echo "Loading TPToolbox-Headless ..."
fastboot flash bootmem TPToolbox-Headless-v004
if [ $? -ne 0 ];
then
	echo "TPToolbox-Headless load failed"
	echo "Aborted."
	exit 1
fi

echo "Waiting for netchip mode... (may take 3+ mins)"
if ! `check_usbdevs 200 ${devid_netchip}`
then
	echo "netchip mode not found"
	echo "Aborted."
	exit 1
fi

echo "Waiting for ping check... (may take 1-2 mins)"
ccnt=120
ping_ok=0
while [ $ccnt -gt 0 ];
do
	ping -c 1 -W 1 192.168.7.7 >/dev/null 2>&1
	if [ $? -eq 0 ];
	then
		ccnt=0
		ping_ok=1
	fi
	ccnt=$(($ccnt - 1))
done
if [ $ping_ok -eq 0 ];
then
	echo "ping check failed"
	echo "check firewall/networking setup"
	echo "access to the 192.68.7.7 host (Touchpad) failed"
	echo "Aborted."
	exit 1
fi

echo "Checking/updating known_hosts..."
need_khosts=0
if [ ! -r ~root/.ssh/known_hosts ];
then
	need_khosts=1
else
	chk1=`ssh-keygen -F 192.168.7.7 -f ~root/.ssh/known_hosts | wc -l`
	if [ $? -ne 0 ];
	then
		echo "Failed to check known_hosts"
		echo "Aborted."
		exit 1
	fi
	if [ $chk1 -eq 0 ];
	then
		need_khosts=1
	fi
fi
if [ $need_khosts -eq 1 ];
then
	mkdir -p ~root/.ssh
	cat khosts >>~root/.ssh/known_hosts
fi

echo "Copying A6 files..."
scp -i ssh-key a6_firmware.txt.00 PmA6Updater root@192.168.7.7:/tmp
if [ $? -ne 0 ];
then
	echo "A6 files copy failed."
	echo "Aborted."
	exit 1
fi

echo "Copying bootloader files..."
scp -i ssh-key bootie-topaz305.bin emmc_appsboot.mbn root@192.168.7.7:/tmp
if [ $? -ne 0 ];
then
	echo "bootloader files copy failed."
	echo "Aborted."
	exit 1
fi

echo ""
echo "Checking A6 firmware..."
ssh -i ssh-key root@192.168.7.7 /tmp/PmA6Updater -x -d 0 /tmp/a6_firmware.txt.00
## if [ $? -ne 0 ];
## then
## 	echo "A6 firmware check failed."
## 	echo "Aborted."
## 	exit 1
## fi

echo ""
echo "Updating A6 firmware..."
ssh -i ssh-key root@192.168.7.7 /tmp/PmA6Updater -f -d 0 /tmp/a6_firmware.txt.00
if [ $? -ne 0 ];
then
	echo "A6 firmware update failed."
	echo "Aborted."
	exit 1
fi

echo ""
echo "Capturing DMESG..."
ssh -i ssh-key root@192.168.7.7 dmesg
if [ $? -ne 0 ];
then
	echo "dmesg capture failed"
	echo "Aborted."
	exit 1
fi

echo ""
echo "Updating bootloader emmc_appsboot..."
ssh -i ssh-key root@192.168.7.7 dd if=/tmp/emmc_appsboot.mbn of=/dev/mmcblk0p7
if [ $? -ne 0 ];
then
	echo "update bootloader emmc_appsboot failed."
	echo "Aborted."
	exit 1
fi

echo ""
echo "Updating bootloader bootie..."
ssh -i ssh-key root@192.168.7.7 dd if=/tmp/bootie-topaz305.bin of=/dev/mmcblk0p8
if [ $? -ne 0 ];
then
	echo "update bootloader bootie failed."
	echo "Aborted."
	exit 1
fi

echo ""
echo "Checking battery voltage/percent... "
bvolt=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getvoltage`
if [ $? -ne 0 ];
then
	echo "getvoltage failed"
	echo "Aborted."
	exit 1
fi
bperc=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getpercent`
if [ $? -ne 0 ];
then
	echo "getpercent failed"
	echo "Aborted."
	exit 1
fi
echo "Battery Voltage=${bvolt} Percent=${bperc}"

if [ $bperc -gt 5 ];
then
	echo "Rebooting Touchpad ..."
	ssh -i ssh-key root@192.168.7.7 "(sleep 1;/sbin/reboot -f) &"
	echo "ALL DONE."
	exit 0
fi

if [ $bperc -gt 0 ];
then
	echo "Rebooting Touchpad ..."
	ssh -i ssh-key root@192.168.7.7 "(sleep 1;/sbin/reboot -f) &"
	echo "Connect touchpad to stock HP AC charger to allow to charge"
	echo "ALL DONE."
	exit 0
fi

echo ""
echo "Waiting 1 min before checking voltage/percent again (1/2) ..."
sleep 60

bvolt=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getvoltage`
if [ $? -ne 0 ];
then
	echo "getvoltage failed"
	echo "Aborted."
	exit 1
fi
bperc=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getpercent`
if [ $? -ne 0 ];
then
	echo "getpercent failed"
	echo "Aborted."
	exit 1
fi
echo "Battery Voltage=${bvolt} Percent=${bperc}"

echo ""
echo "Waiting 1 min before checking voltage/percent again (2/2) ..."
sleep 60

bvolt=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getvoltage`
if [ $? -ne 0 ];
then
	echo "getvoltage failed"
	echo "Aborted."
	exit 1
fi
bperc=`ssh -i ssh-key root@192.168.7.7 cat /sys/devices/i2c-3/3-0031/getpercent`
if [ $? -ne 0 ];
then
	echo "getpercent failed"
	echo "Aborted."
	exit 1
fi
echo "Battery Voltage=${bvolt} Percent=${bperc}"

echo "Rebooting Touchpad ..."
ssh -i ssh-key root@192.168.7.7 "(sleep 1;/sbin/reboot -f) &"
echo "Connect Touchpad to stock HP AC charger now"
echo "and allow it to charge for several hours"
echo "ALL DONE."
