#!/usr/bin/perl                                                                 
use LWP::Simple;

my $turn_off = "http://192.168.1.51/?sc=0&pw=$password";
my $turn_on  = "http://192.168.1.51/?sc=1&pw=$password";
my $url = "http://192.168.1.51/?sw=1";
my $action = "";
my $state = "";

my $debug = 1;


sub do_execute() {
    my ($the_url) = @_;
    my $content = get($the_url); #Get web page in content 
        die "get failed" if (!defined $content);

    my @w2 = split(/\n/, $content);
    my @s1 = split(/\s+/, $w2[3]);
    if (!substr(@s1[5],length(@s1[5])-2,1)) {
        $state = "on";
    } else {
        $state = "off";
    }
#   print $state ."\n";
    return $state;
}
    


if (exists($ARGV[0])) {
    if ($ARGV[0] eq "on") {
	do {
	    $state = &do_execute($turn_on); #Get web page in content
	    sleep 1;
            $state = &do_execute($url);
	} until ($state eq "on");
	$debug = 0;
    }

    if ($ARGV[0] eq "off") {
	do {
	    $state = &do_execute($turn_off); #Get web page in content
            sleep 1;
	    $state = &do_execute($url); 
	} until ($state eq "off");
	$debug = 0;
    }

    if ($ARGV[0] eq "-h") {
	print "Sätta på/stänga av elpatron eller visa status.\n\n";
	print "elpatron.pl [on|off]\n\n";
	$debug = 0;
    }
}

if (exists($ARGV[1])) {
    $debug = 1;
}

if ($debug) {
    my $state = &do_execute($url);
    print "Elpatron: " . $state ."\n";
}

#if (exists($ARGV[1])) {
#    print $content . "\n\n";
#}

#<a href=./>[home]</a> <a href=./?sw=1>[refresh]</a>
#<h2>Switch</h2>
#<pre>state: OFF
#<form action=/ method=get><input type=hidden name=sc value=1>
#passw: <input type=password size=10 name=pw><input type=submit value="switch on"></form>
#</pre><hr>

#<a href=./>[home]</a> <a href=./?sw=1>[refresh]</a>
#<h2>Switch</h2>
#<pre>state: <font color=#00FF00>ON</font>
#<form action=/ method=get><input type=hidden name=sc value=0>
#passw: <input type=password size=10 name=pw><input type=submit value="switch off"></form>
#</pre><hr>