#! /usr/bin/awk -f

# Based on the original script from noggie, stripped not used
# parts. More functionality can be placed here

function vsystem(cmd) {
	if (verbose) print cmd
	# Work around a very strange bug somewhere.
	cmd = cmd ";echo $?>/tmp/shstatus"
	system(cmd)
	getline system_rtn < "/tmp/shstatus"
	close("/tmp/shstatus")
	system_rtn = system_rtn + 0
	return system_rtn
}


function decode_cmdline(normalized, cmdline)
{
	split(normalized, tmp1, "&")
	for (i in tmp1) {
		split(tmp1[i], tmp2, "=")
		cmdline[tmp2[1]] = tmp2[2]
	}
}


BEGIN {
	# Set to 0 for less verbose output
	verbose = 1
	# Prepare to read the multipart/form-data input
	RS = "\r\n"
	IGNORECASE = 1
	decode_cmdline(ENVIRON["QUERY_STRING"], cmdline)
	command = cmdline["command"]
	param = cmdline["param"]
	param2 = cmdline["param2"]

	# print headers
	print "Content-Type: text/plain"
	print "Cache-control: no-cache"
	print "Cache-control: no-store"
	print "Pragma: no-cache"
	print "Expires: 0"
	print ""

	if (command == "reboot") {
		print "ok"
		fflush()
		system("sleep 1")
		vsystem("front_ioctl --job reboot")
	}
	
	if (command == "poweroff") {
		print "ok"
		fflush()
		system("sleep 1")
		vsystem("front_ioctl --job poweroff")
	}
		
	if (command == "turnon") {
		print "ok"
		fflush()
		vsystem("/usr/bin/killall front_pwr_manager")
	}
		
	else if (command == "check_on") {
		print " " | "ps | grep bin/relook | grep -v grep | wc -l"
	}
				
	else if (command == "change_channel") {
		nb=split(param,cdigit,"")
		desc=nb
		zeros=4-nb
		while (zeros > 0) {
			system("cat ./commands/0  > /dev/input/event0")
			zeros--
		}	
		while (desc >= 1) {
			cmd=("cat ./commands/" cdigit[nb-desc+1] " > /dev/input/event0")
			desc--
			system(cmd)
		}
		print "ok"
	}
				     	
	else if (command == "send_command") {
		cmd=("cat ./commands/" param " > /dev/input/event0")
		system(cmd)
		print "ok"
	}
	
	else if (command == "print_message"){
		cmd=("echo show_mess " param " > /dev/commander")
		system(cmd)
		print "ok"
	}
	
	else if (command == "date") {
		print " " | "date \"+%s\""
	}
	
	else if (command == "mv")	{
		cmd=("mv " param)
		vsystem(cmd)
	}
	

} #ENDBEGIN
