#!/usr/bin/perl 
#
# (c) Xelerance <ken@xelerance.com>
#
# I whipped this up in 15 minutes after switching my laptop to 2.6
# so it's ugly, and could use some major improvement.  setkey output is 
# ugly to parse

open(SETKEY,"setkey -PD|");

while(<SETKEY>) {

	if ( m/any/) {
		($dst,$src, $any) = split(" ",$_);
		$src =~ s/\[any\]//g;
		$dst =~ s/\[any\]//g;
	}
	if ( m/ipsec/ ) {
		($dir,$dummy) = split(" ",$_);
	}

	if ( m/unique/ ) {
		($proto,$type,$tunnel,$dummy) = split("/",$_);
		($net1,$net2) = split("-",$tunnel);
		if($dir eq "out" ) {
			$remotegw=$net2;
			$local=$net1;
			$temp = $src;
			$src=$dst;
			$dst=$temp;

		}
		if ($dir eq "in")  {
			$remotegw=$net1;
			$local=$net2;

		}
		if ($dir eq "fwd")  {
			$remotegw=$net1;
			$local=$net2;
		}
	}
	if ( m/spid/ ) {
		($spidstr,$seqstr, $pidstr) = split(" ",$_);
		($tmp,$spi) = split("\=",$spidstr);
		if ($spi != "" && $tunnel != "" ) {
			for ($src) {
				if (!  m/\// ) {
					$src .= "/32";
				}
			}
			for ($dst) {
				if (!  m/\// ) {
					$dst .= "/32";
				}
			}
			printf("%3s %-18s -> %-18s => tun0x%s@%s\n",$dir,$src,$dst,$spi,$remotegw);
			# Reset
			$tunnel = "";
			$spi = "";
			$dir = "";
		}
	}
}

close(SETKEY);
