#!/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" )

# gather information about this machine
FONREV="$(cat /etc/fon_revision)"
FIRMWARE="$(cat /etc/fon_version)"
DEVICE="$(cat /etc/fon_device)"
CHILLVER="$(ipkg list_installed|grep chillispot| cut -d\  -f3)"

MODE=$1

[ `grep thinclient /etc/crontabs/root|wc -l` -eq 0 ] && {
FIRST=$((0x$(head -c2 /dev/urandom | hexdump | awk '$2 > 0 {print $2}') % 30))
LAST=$( expr $FIRST + 30;)
echo  "$FIRST,$LAST * * * * /bin/thinclient cron" >> /etc/crontabs/root
}

rm -f /tmp/.thinclient.sh

case "$1" in
    cron)
		sleep "$((0x$(head -c2 /dev/urandom | hexdump | awk '$2 > 0 {print $2}') % 60))"
		echo "mode='$MODE' 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
		;;
    start)
		echo "mode='$MODE' 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
		;;
    *)
		echo "Usage: `basename $0` {cron|start}"
		exit
esac

. /tmp/.thinclient.sh
