#!/usr/bin/perl 
##################################################
#####     VPN-Watch.pl     Version 0.5       #####
##################################################
#                                                #
#   VPN-Watch is part of the IPFire Firewall     #
#                                                #
##################################################

use strict;

require '/var/ipfire/general-functions.pl';
my @vpnsettings;
my $i = 0;
my $file = "/var/run/vpn-watch.pid";
my $debug = 0;

if ( -e $file ){
  logger("There my be another vpn-watch runnning because $file exists, vpn-watch will try kill the process.");
  open(FILE, "<$file");
    my $PID = <FILE>;
    close(FILE);
    system("kill -9 $PID");
  }

system("echo $$ > $file");
my $round=0;
while ( $i == 0){
  if ($debug){logger("We will wait 60 seconds before next action.");}
    sleep(60);

  $round++;

   # Reset roundcounter after 10 min. To do established check.
  if ($round > 9) { $round=0 }

  if (open(FILE, "<${General::swroot}/vpn/config")) {    @vpnsettings = <FILE>;
    close(FILE);
    unless(@vpnsettings) {exit 1;}
  }

my $status = `ipsec whack --status`;
foreach (@vpnsettings){
 my @settings = split(/,/,$_);

  if ($settings[27] ne 'RED'){next;}
  if ($settings[4] ne 'net'){next;}  
  if ($settings[1] ne 'on'){next;}chomp($settings[29]);
  if ($settings[29] ne 'on'){next;}
 
  my $remotehostname = $settings[11];
  
  if ($debug){logger("Checking connection to $remotehostname.");}
  
  my $remoteip = `/usr/bin/ping -c 1 $remotehostname 2>/dev/null | head -n1 | awk '{print \$3}' | tr -d '()' | tr -d ':'`;chomp($remoteip);
  if ($remoteip eq ""){next;if ($debug){logger("Unable to resolve $remotehostname.");}}
  my $ipmatch= `echo "$status" | grep '$remoteip' | grep '$settings[2]'`;
  my $established= `echo "$status" | grep '$settings[2]' | grep 'erouted;'`; 
  
  if ( $ipmatch eq '' ){
    logger("Remote IP for host $remotehostname($remoteip) has changed, restarting ipsec.");
    system("/usr/local/bin/ipsecctrl S $settings[0]");
    last; #all connections will reloaded
          #remove this if ipsecctrl can restart single con again
  }
  if ( ($round = 0) && ($established eq '')) {
    logger("Connection to $remotehostname($remoteip) not erouted, restarting ipsec.");
    system("/usr/local/bin/ipsecctrl S $settings[0]");
    last; #all connections will reloaded
          #remove this if ipsecctrl can restart single con again

  }
 }
 if ($debug){logger("All connections may be fine nothing was done.");}
}

sub logger {
        my $log = shift;
        system("logger -t vpnwatch \"$log\"");
}
