#!/bin/sh

set -x

TMP_FILE=/tmp/rnas.activation
TIMEOUT=10
TOTAL_TIME=0
SLEEP_INTERVAL=1
PCB_OBJECT_PATH='AP.USB'
PCB_CMD=pcb_cli
PCB_NOTIFICATION_TYPE=102
PCB_NOTIFICATION_NAME='usb_notification_device_deleted'

EN_MSG="Remote Access Account Pairing<br>Please press \\\\\\\"OK\\\\\\\" to pair your Remote Access Data Account with your Internet-Box."
FR_MSG="Remote Access Account Pairing<br>Please press \\\\\\\"OK\\\\\\\" to pair your Remote Access Data Account with your Internet-Box."
DE_MSG="Remote Access Account Pairing<br>Please press \\\\\\\"OK\\\\\\\" to pair your Remote Access Data Account with your Internet-Box."
IT_MSG="Remote Access Account Pairing<br>Please press \\\\\\\"OK\\\\\\\" to pair your Remote Access Data Account with your Internet-Box."

CMD_FMT="{\\\\\"Language\\\\\":\\\\\"%s\\\\\",\\\\\"Description\\\\\":\\\\\"<font size=\\\\\\\\\\\\\"22\\\\\\\\\\\\\">%s<br></font><item text=\\\\\\\\\\\\\"Allow Pairing\\\\\\\\\\\\\" value=\\\\\\\\\\\\\"Allowed\\\\\\\\\\\\\"/><button id=\\\\\\\\\\\\\"back\\\\\\\\\\\\\" value=\\\\\\\\\\\\\"Denied\\\\\\\\\\\\\"/>\\\\\"}"
CMD_EN=`printf "$CMD_FMT" "EN" "$EN_MSG"`
CMD_FR=`printf "$CMD_FMT" "FR" "$FR_MSG"`
CMD_DE=`printf "$CMD_FMT" "DE" "$DE_MSG"`
CMD_IT=`printf "$CMD_FMT" "IT" "$IT_MSG"`

pcb_cli "AP.LCD.addEvent(\"[$CMD_EN, $CMD_FR, $CMD_DE, $CMD_IT]\", 1, true, false, $TIMEOUT)"

EVENT_ID=$?

REGEX="/AP\.USB\.Device\.[0-9]+\[$PCB_NOTIFICATION_NAME\|$PCB_NOTIFICATION_TYPE\]{ID=([0-9]+)}$/"

script -q -f $TMP_FILE -c "echo '$PCB_OBJECT_PATH.?&' | $PCB_CMD | awk 'match("'$0'", $REGEX, a) {print a[1]}'" > /dev/null &

touch $TMP_FILE
LAST_MOD_DATE=`date -r $TMP_FILE +%s`

while [ $LAST_MOD_DATE -eq `date -r $TMP_FILE +%s` ]
do
	sleep $SLEEP_INTERVAL
	let "TOTAL_TIME = $TOTAL_TIME + $SLEEP_INTERVAL"
	if [ $TOTAL_TIME -gt $TIMEOUT ]
	then
		break
	fi
done

RESPONSE=`tail -n 1 $TMP_FILE`

case "$RESPONSE" in
*1*)
	echo -n "ALLOW"
	break
	;;
*2*)
	echo -n "REJECT"
	break
	;;
*)
	echo -n "ERROR"
	break
	;;
esac

rm $TMP_FILE

exit 0
