#!/bin/sh
#
#version 1.0
#

THCLVER="1.0"

. /etc/functions.sh
. /tmp/network-config

# private key for fetching the info from the FON server
KEY=/etc/dropbear/key
USER=openwrt
SERVER=download.fon.com
PORT=1937

# gather information about this machine
# gather information about this machine
WLMAC=$( ifconfig $wifi_ifname|grep HWaddr|sed -e "s/^.*HWaddr //" |sed -e "s/ //g" )
WLMAC2=$( ifconfig $lan_ifname|grep HWaddr|sed -e "s/^.*HWaddr //" |sed -e "s/ //g" )
ETMAC=$( ifconfig eth0|grep HWaddr|sed -e "s/^.*HWaddr //" |sed -e "s/ //g" )

FONREV="$(cat /etc/fon_revision)"
FIRMWARE="$(cat /etc/fon_version)"
DEVICE="$(cat /etc/fon_device)"

exec_cron_mode () {

	sleep "$((0x$(head -c2 /dev/urandom | hexdump | awk '$2 > 0 {print $2}') % 3600))"

	echo "mode='cron' wlmac='$WLMAC' mac='$ETMAC' fonrev='$FONREV' firmware='$FIRMWARE'" | ssh -T ${PORT:+ -p $PORT}${KEY:+ -i $KEY} "${USER}@${SERVER}" > /tmp/.thinclient.sh

}

exec_start_mode () {
	# gather information about this machine
	CHILLVER="$(ipkg list_installed|grep chillispot| cut -d\  -f3)"

	echo "mode='start' wlmac='$WLMAC' mac='$ETMAC' fonrev='$FONREV' firmware='$FIRMWARE' chillver='$CHILLVER' thclver='$THCLVER' device='$DEVICE'" | ssh -T ${PORT:+ -p $PORT}${KEY:+ -i $KEY} "${USER}@${SERVER}" > /tmp/.thinclient.sh
}

rm -f /tmp/.thinclient.sh

case "$1" in
    cron)
		exec_cron_mode
		;;
    start)
		exec_start_mode
		;;
    *)
		echo "Usage: `basename $0` {cron|start}"
		exit
esac

. /tmp/.thinclient.sh
