#!/usr/bin/perl -w

# Quick-and-dirty script to remain connected to the Pitt network, using /etc/init.d/net.$INTERFACE.
# You need my /etc/conf.d/net and my pingwait script.
# Set the shell variable $INTERFACE to the interface you want to use, or let the script default to eth0.
# Also, you may need to set the location of pingwait if it's not in your PATH or /usr/local/bin/pingwait.
#
# Chris Povirk -- beige tangerine (AT) g mail (DOT) com
# http://twofoos.org/content/wpa_supplicant/
# 2007/02/14

use strict;

use POSIX 'setsid';

my $INTERFACE = $ENV{INTERFACE} || 'eth0';
chomp ( my $PINGWAIT = `which pingwait 2> /dev/null || echo /usr/local/bin/pingwait` );

my $LOGFILE = '/var/log/beconnected.log';

my $INTERVAL = 15;
my $WAIT = 5;

#my $DESTINATION = 'www.google.com';
#my $DESTINATION = 'externals-cl.gw.pitt.edu';
my $DESTINATION = 'externals-fq.gw.pitt.edu';
#my $DESTINATION = 'cl2-vlan300.gw.pitt.edu';

# daemonize() from perlipc
sub daemonize()
{
  chdir '/'               or die "Can't chdir to /: $!";
  open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
  open STDOUT, '>/dev/null'
    or die "Can't write to /dev/null: $!";
  defined(my $pid = fork) or die "Can't fork: $!";
  exit if $pid;
  setsid                  or die "Can't start a new session: $!";
  open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}

daemonize();

my @ping = qq/$PINGWAIT $DESTINATION $WAIT/;

my @netRestart = qq{/etc/init.d/net.$INTERFACE restart};

#system(qq/echo >> $LOGFILE/);
#system(qq/date >> $LOGFILE/);
system(@ping) == 0 || system(@netRestart);

while(1)
{
#  system(qq/echo >> $LOGFILE/);
#  system(qq/date >> $LOGFILE/);
  unless(system(@ping) == 0)
  {
    unless(system(@ping) == 0)
    {
      system(qq/date >> $LOGFILE/);
      system(qq/echo "Reconnecting" >> $LOGFILE/);
      until(system(@netRestart) == 0) {}
      system(qq/echo >> $LOGFILE/);
    }
  }
  sleep $INTERVAL;
}
