# The intent here is to force a net connect of an RTV going through
# a Wirns proxy to prevent unwanted software download. I don't want to
# leave the Wirns proxy running 24/7 so use this to automate daily
# forced net connects, through the proxy.
# The Wirns proxy should have the NoSoftwareUpdate.dll plugin installed.
# This Perl script will start the Wirns proxy and then issue a forced
# net connect to specified RTV IP that is setup with manual settings
# with DNS pointing at the Wirns IP, and then kill the Wirns proxy
# once the net connect completes.
# NOTE: This script is win32-specific.
# NOTE: Remember to kill anything running on port 80 (such as DVA)
#       before running this - else Wirns won't start.

use Win32::Process;
require LWP::UserAgent;
require HTTP::Request;

# Adjust these for your environment
local $RTVIP = "192.168.1.5";
local $WIRNSDIR = "C:\\home\\wirns";
local $NETCONNECT_SLEEP = 300; # time to wait for netconnect to finish (secs)

# Don't need to mess with these
local $WAKEUP_SLEEP = 10;
local $WIRNS = $WIRNSDIR . "\\WiRNS.exe";
local $CALL = "WiRNS -server";
local $TIMEOUT = 20;

### START MAIN ###
# Turn off buffering
$| = 1;

# Sleep a while to give a chance to wake up from sleep mode
print "Sleeping a little in case waking up from sleep mode...\n";
sleep($WAKEUP_SLEEP);

# Start Wirns as a background child process
local $CHILD;
&startChild(\$CHILD,$WIRNS,$CALL,$WIRNSDIR);

# Force net connect for $RTVIP
&netConnect($RTVIP);

# Kill Wirns and exit
print "Killing Wirns\n";
$CHILD->Kill(0);
exit(0);
### END MAIN ###

sub startChild {
 my ($child, $prog, $call, $dir) = @_;
   my $result = Win32::Process::Create(
      $$child, $prog, $call, 0, CREATE_NEW_CONSOLE, $dir
   );
   die "Failed to start: $prog\n" if ! $result;

   # Give a few moments for process to start
   sleep(5);
}

sub netConnect {
 my $IP = shift;
   $on = 200;
   $off = 201;
   $exit = 164;
   $two = 182;
   $three = 183;
   $four = 184;
   $seven = 187;
   $zone = 197;
   @sequence = ($on, $exit, $exit, $two, $four, $three, $zone, $seven);
   my $prefix = "http://$IP/httputils-sendciomessage?cioc=";
   my $ua = LWP::UserAgent->new(timeout=>$TIMEOUT);
   my $request;
   foreach $code (@sequence) {
      $query = $prefix . $code;
      sleep(1);
      print "$query\n";
      $request = HTTP::Request->new(GET=>$query);
      $ua->request($request);
   }

   # sleep for a while
   sleep($NETCONNECT_SLEEP);

   # Exit and turn off RTV
   @sequence = ($exit, $off);
   foreach $code (@sequence) {
      $query = $prefix . $code;
      sleep(1);
      print "$query\n";
      $request = HTTP::Request->new(GET=>$query);
      $ua->request($request);
   }
}
