#!/usr/bin/env perl
#!/usr/bin/perl -T
# Click My Light, light.cgi

use Socket;

## Start user config
#
# host that controls light
$host = "a.host.arpa";          
# on port
$on_port = "8000";
# off port
$off_port = "8001";
# file that contains the light's current status
$status = "/tmp/.light.status";
#
# End user config

# Setup
#
select STDOUT;
$| = 1;

# Print MIME
#
print "Content-type:text/html\n\n";

# Send data
#
sub Send {
my($in_addr,$addr,$proto);

open ST, ">$status" or print "Can't open $status: $!\n";
        print ST "$value\n";
close ST;

$in_addr = (gethostbyname($host))[4];
$addr = sockaddr_in($port, $in_addr);
$proto = getprotobyname('tcp');

socket(Server, AF_INET, SOCK_STREAM, $proto) or print "socket: $!\n";    
connect(Server, $addr) or print "connect: $!\n";
select Server;
send(Server, "", MSG_OOB);
close Server;
}

# blah
#
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs = split(/&/, $buffer);
		foreach $pair (@pairs) {
    		  ($name, $value) = split(/=/, $pair);
    		  $value =~ tr/+/ /;
    		  $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    		  $FORM{$name} = $value;
}

$value =~ tr/a-z//csd;

if ($value eq "on") {
		&Send($port = $on_port);
}

elsif ($value eq "off") {
		&Send($port = $off_port);
}

else {
	$value = "broken";
}

# Setup
#
select STDOUT;
$| = 1;                       

# Draw me a web page
#
print <<END_OF_FILE;
<html>
<title>Results</title>
<body>
<font size="6">
The light is now <b>$value</b>, or should be.<br>
</body>
</html>
END_OF_FILE