#!/bin/bash
#
# Automatic upgrading BR6104K(P) & XRT401D to FlyRouter (c) Vlad (20071101)
#
# ./upload-fly -noboot
# ./upload-fly-new -m=xrt401d -i=fly-default-ovpn.bin.csys -a=amilda-middle-br6104k.bin 1

server_iface="eth0"
server_ip="192.168.1.2"
server_url="http://${server_ip}/build/"
amilda_image="firmware/flyrouter_helper/amilda-middle-br6104k.bin"
bootloader="bootloader/flyrouter/bootloader-fly.bin"
fly_default_ip="192.168.1.1"
amilda_default_ip="192.168.1.1"

rgb_restore='\033[00m'
rgb_black='\033[00;30m'
rgb_firebrick='\033[00;31m'
rgb_red='\033[01;31m'
rgb_forest='\033[00;32m'
rgb_green='\033[01;32m'
rgb_brown='\033[00;33m'
rgb_yellow='\033[01;33m'
rgb_navy='\033[00;34m'
rgb_blue='\033[01;34m'
rgb_purple='\033[00;35m'
rgb_magenta='\033[01;35m'
rgb_cadet='\033[00;36m'
rgb_cyan='\033[01;36m'
rgb_gray='\033[00;37m'
rgb_white='\033[01;37m'
move_cursor='\033[80;80f'

fail () { echo -e "  ${move_cursor}[ ${rgb_red}FAIL${rgb_restore} ] " $@ >&2; exit 1; }
warn () { echo -e "  ${move_cursor}[ ${rgb_yellow}WARN${rgb_restore} ] " $@ >&2; }
ok   () { echo -e "  ${move_cursor}[  ${rgb_green}OK${rgb_restore}  ] " $@ >&2; }
log  () { echo $@ | logger -t fly-upload; }
required() {  prg=`which $1`; echo -n "Looking for $prg"; test -x "$prg" && ok || fail "$0: Error $1 is required"; }

clear

required ip
required curl
required wget
required hexdump
required tempfile
required expect
required telnet
required aplay # alsa-utils

#check-only: hexdump tempfile aplay
#apt-get install iproute curl wget expect telnet arping picocom

usage() {
	echo -e "Usage: $0 -m <model> [-n] [-i <imagefile>] [-a <amildaimage>] [123]"
	echo -e "\t-m - model of router: {xrt412|xrt401d|br6104k|br6104kp}"
	echo -e "\t-n - do not rewrite bootloader"
	echo -e "\t-a - use amilda image"
	echo -e "\t-i - use image file"
	exit 0;
}

check_alive() {
	local ip="$1"
	local msg="$2"
	echo -n "Checking for alive..."
	for i in 1 2 3 4 5 6 7 8 9 10; do
		echo -n "."
		ping -c 2 -q ${ip} >/dev/null 2>&1 && { ok; break; }
		[ $i = 10 ] && fail "$msg"
		sleep 3;
	done
}

set_ip() {
    # check by ARP another hosts with this ip
    # check on interfaces
    ip a add 192.168.0.2/24 dev $server_iface
    ip a add 192.168.1.2/24 dev $server_iface
    ip a add 192.168.2.2/24 dev $server_iface
}

help() {
    echo -e "\nPlease select menu:\n"
    echo "1  - OpenVPN firmware"
    echo "1a - OpenVPN firmware by stage2..."
    echo "2  - GSM/GPRS firmware"
    echo "2a - GSM/GPRS firmware by stage2..."
    echo "3  - Stas firmware"
    echo "3a - Stas firmware by stage2..."
    echo "h  - Get help"
    echo "q  - Quit"
}

stage1() {
	set_ip
	echo 
	echo -e "      ${rgb_white}Stage 1${rgb_restore}"

	echo -n "Clearing ARP cache"
	ip ne flush dev $server_iface && ok || fail

	# check router_default_ip
	echo -n "Checking router ip: $router_default_ip"
	[ -n "$router_default_ip" ] && ok || fail "Please use -model option"

	# check alive
	check_alive ${router_default_ip} "Original firmware is not alive (${router_default_ip})"

	echo -n "HTTP alive..."
	{ curl -s "${router_default_url}/index.asp" 2>&1 | grep "Broadband Router" >/dev/null; } && ok || fail 

	echo -n "Checking upgrade page..."
	{ curl -s "${router_default_url}/tlaccept.asp" 2>&1 | grep "The system will automatically reboot" >/dev/null; } && ok || fail 

	echo -n "Looking for amilda-middle image..."
	[ -r "${amilda_image}" ] && ok || fail

	echo -n "Checking amilda-middle image..."
	[ "`hexdump ${amilda_image} | head -n 1 | cut -d" " -f2`" = 4257 ] && ok || fail

	echo -n "Uploading image..."
	{ curl -s --form "binary=@${amilda_image};type=application/octet-stream" \
			--form "submit-url=/tlaccept.asp" \
				"${router_default_url}/goform/formUpload" | grep "Update successfully" >/dev/null; } && ok || fail

	echo -n "Waiting..."
	sleep 60 && ok
}

stage2() {
	set_ip
	echo 
	echo -e "      ${rgb_white}Stage 2${rgb_restore}"

	echo -n "Clearing ARP cache"
	ip ne flush dev $server_iface && ok || fail
	
	expect_login_code="set timeout 12; proc fail {} { exit 1; }; spawn telnet ${amilda_default_ip}; expect { timeout fail; login }; send root\r; expect { timeout fail; Password }; send 1234\r; expect { '#' };"

	check_alive ${amilda_default_ip} "AMiLDA is not alive (${amilda_default_ip})"

	tmp=/tmp/upload-fly-$$-`date +%s`

	echo -n "Checking for ${image}"
	wget -q ${server_url}/${image} -O $tmp || fail "cannot download ${server_url}/${image}"
	[ "`hexdump ${tmp} | head -n 1 | cut -d" " -f2`" = 5343 ] && ok || fail

	echo -n "Checking for ${bootloader}"
	wget -q ${server_url}/${bootloader} -O $tmp || fail "cannot download ${server_url}/${bootloader}"
	[ "`hexdump ${tmp} | head -n 1 | cut -d" " -f2`" = 6000 ] && ok || fail

	echo  "Logging in..."
	#expect -c "${expect_login_code} send ps\n; expect { '#' }; send exit\n" | tee $tmp

	echo 
	#echo -n "Checking login..."
	#cat $tmp | grep "telnetd" >/dev/null  && ok || fail

	expect -c "${expect_login_code} set timeout 10; send \"rm -rf /web /bin/ppp* /bin/iptables /bin/ip6tables && sleep 1\n\" ; expect { ' #' }; send exit\n" | tee $tmp
	expect -c "${expect_login_code} set timeout 60; send \"wget ${server_url}/${image} -O /tmp/image.bin && dd if=/tmp/image.bin of=/dev/mtd_midge\n\" ; expect { records }; send exit\n" | tee $tmp
	[ -z "$noboot" ] &&
	expect -c "${expect_login_code} set timeout 15; send \"wget ${server_url}/${bootloader} -O /tmp/boot.bin && dd if=/tmp/boot.bin of=/dev/mtd_bootrw \n\" ; expect { records }; send exit\n" | tee $tmp
	expect -c "${expect_login_code} set timeout 5; send \"reboot\n\" ; expect { ' #' }; send exit\n" | tee $tmp

	echo -n "Waiting..."
	sleep 90 && ok

}

stage3() {
	set_ip
	echo 
	echo -e "      ${rgb_white}Stage 3${rgb_restore}"

	echo -n "Clearing ARP cache"
	ip ne flush dev $server_iface && ok || fail
	check_alive ${fly_default_ip} "FLY is not alive (${fly_default_ip})"

	# by Zig
	sleep 60
	clear
	ping -q -c 1 ${fly_default_ip} && rm -rf /root/.ssh/known_hosts
	expect_ssh_code="set timeout 10; proc fail {} { exit 1; }; spawn ssh root@${fly_default_ip}; expect { timeout fail; Are you sure you want to continue connecting (yes/no)? }; send yes\r; expect { timeout fail; Password }; send 1234\r; expect { '#' };"
	expect -c "${expect_ssh_code} set timeout 10; send \"flash save\n\" ; expect { ' #' }; send \"boot\n\" ; expect { ' #' }; send \"cat /etc/banner\n\" ; expect { ' #' }; send \"ls -la /etc/dropbear | grep -e ".key"\n\" ; expect { ' #' }; send exit\n"
	aplay /usr/share/orage/sounds/Phone.wav
}

while getopts "nhi:m:a:123" opt; do
	case $opt in
		h) usage; exit 0;;
		n) noboot=yes;;
		i) image="$OPTARG";;
		a) amilda_image="$OPTARG";;
		m) model="$OPTARG"
		case ${model} in
			xrt412) 
				router_default_ip="192.168.0.1"
				router_default_url="http://admin:1234@${router_default_ip}"
				amilda_image="amilda-middle-br6104kp.bin"
				;;
			xrt401d) 
				router_default_ip="192.168.0.1"
				router_default_url="http://admin:1234@${router_default_ip}"
				amilda_image="amilda-middle-br6104k.bin"
				;;
			br6104k) 
				router_default_ip="192.168.2.1"
				router_default_url="http://admin:1234@${router_default_ip}"
				amilda_image="amilda-middle-br6104k.bin"
				;;
			br6104kp) 
				router_default_ip="192.168.2.1"
				router_default_url="http://admin:1234@${router_default_ip}"
				amilda_image="amilda-middle-br6104kp.bin"
				;;
		esac
		;;
		1) stage1; stage2; stage3; exit 0;;
		2) stage2; stage3; exit 0;;
		3) stage3; exit 0;;
		*) usage;;
	esac
done


usage


echo -e "\nWelcome to Fly-Upload script..."
cd /var/www/build
help


while true ; do
    echo -n -e "\n[`date +%H:%M`] -->"
    read COMMAND
    ANSWER=`echo $COMMAND`
case $ANSWER in 

#-------
    1)
        echo ""
	echo "Select OpenVPN firmware..."
	image="firmware/flyrouter_full/fly-default-ovpn.bin.csys"
	stage1
	stage2
	stage3
        ;;
#-------
    1a)
        echo ""
	echo "Select OpenVPN firmware by stage2..."
	image="firmware/flyrouter_full/fly-default-ovpn.bin.csys"
	stage2
	stage3
        ;;
#-------
    2)
        echo ""
	echo "Select GSM/GPRS firmware..."
	image="firmware/flyrouter_full/fly-default-office.bin.csys"
	stage1
	stage2
	stage3
        ;;
#-------
    2a)
        echo ""
	echo "Select GSM/GPRS firmware by stage2..."
	image="firmware/flyrouter_full/fly-default-office.bin.csys"
	stage2
	stage3
        ;;
#-------
    3)
        echo ""
	echo "Select Stas firmware..."
	image="firmware/flyrouter_full/fly-default-stas.bin.csys"
	stage1
	stage2
	stage3
        ;;
#-------
    3a)
        echo ""
	echo "Select Stas firmware by stage2..."
	image="firmware/flyrouter_full/fly-default-stas.bin.csys"
	stage2
	stage3
        ;;

#-------
    q)
        echo ""
        echo -e "\nGood bye, 73.\n"
        exit 0
        ;;
#-------
    h)
        echo ""
	help
        ;;

#-------
    *)
        ;;
esac

done
