#! /usr/bin/awk -f

# Based on original by noggie

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
}


BEGIN {
	verbose = 1
	RS = "\r\n"
	IGNORECASE = 1

	# Decode form data, store form variables in "vals"
	while ((getline line) > 0) {
		if (match(line, "^---")) {
			# Expect headers
			while ((getline line) > 0) {
				if (match(line, "^content-disposition:")) {
					n = match(line, "name=", line)
					rmd = substr(line, n + 5)
					gsub("\"", "", rmd)
					if ((getline val) <= 0) break
					if ((getline val) <= 0) break
					gsub("^ +", "", val)
					gsub(" +$", "", val)
					vals[rmd] = val
				}
			}
		}
	}
	

	if (vals["img_type"] == "img")  {
		print "Please be patient while the relook reboots and burns the new "
		print "firmware (this may take some time)"
		fflush()
				
		vsystem("echo /tmp/image.img > /tmp/images")
		vsystem("cat rebootcmd > /dev/input/event0")
	
		print "\n"
		print "If your relook does not reboot by itself now, your firmware "
		print "does not support this way of upgrading. "
		print "In this case you must open a telnetconnection to your relook,"
		print "and execute '/usr/bin/update.sh /tmp /tmp/images' manually.\n"
	
	}	else {
		print "Error in form data.. nothing happened."
		exit 1
	}
}
