#!/usr/bin/perl

use strict;
use HTTP::Request::Common;
use LWP::UserAgent;

die ('no command argument given') if (!$ARGV[0]);

my $url = 'http://192.168.5.1/apply.cgi';

my $ua = new LWP::UserAgent;
my $wl_net_mode;

my $do_something = 0;

if (($ARGV[0] eq 'off') && (get_wlan_state () eq 1))
{
  $do_something = 1;
  $wl_net_mode = 'disabled';
  # touch status file if WLAN is turned OFF manually
  if ($ARGV[1] eq 'manual')
  {
    `touch '/tmp/wlan-manual-off'`;
  }
}
elsif (($ARGV[0] eq 'on') && (get_wlan_state () eq 0))
{
  $do_something = 1;
  $wl_net_mode = 'mixed';
  # WLAN will be turned ON manually - remove manually OFF status file
  if ($ARGV[1] eq 'manual')
  {
    unlink '/tmp/wlan-manual-off';
  }
  # don't turn ON automatically if WLAN was turned OFF manually before
  elsif (-e '/tmp/wlan-manual-off')
  {
    $do_something = 0;
  }
}

my $req = POST $url, [ 'wl_mode' => 'ap', 'wl_ssid' => 'Owezahrer', 'wl_net_mode' => $wl_net_mode, 'submit_button' => 'Wireless_Basic', 'action' => 'Apply', 'commit' => '1' ];

$req->authorization_basic('admin','secret');
$req->content_type('form-data'); 

if ($do_something == 1)
{
  my $this = $ua->request ($req);
}

# DEBUG ?!
# print "OK. WLAN: " . $wl_net_mode . "\n";

sub get_wlan_state ()
{

  my $url = 'http://192.168.5.1/Wireless_Basic.asp';
  my $ua = new LWP::UserAgent;
  my $req = GET $url;
  $req->authorization_basic('admin','secret');
  my $this = $ua->request ($req);
  my @list = split /\n/, $this->content;
  my @result = grep {/<option value="disabled" >Disabled<\/option>/} @list;

  return 1 if ($#{@result} eq 0);
  
  return 0;
  
}
