#!/usr/bin/perl

# PacketiX セキュアインターネット接続 自動接続スクリプト
# perlだけで無理やりやってみた版 0.0.2

use Data::Dumper;

# VPN接続のインターフェイス
$vpnif = 'vpn_001';

# VPN Clientのパス
$daemon = '/usr/local/vpnclient/vpnclient';

# コマンドラインマネージャのパス
$vpncmd = '/usr/local/vpnclient/vpncmd';

# セキュアインターネット接続の名前
$conname = 'セキュアインターネット接続';

# public.softether.com が所属するネットワーク
$vpnnet = '130.158.0.0';

# 仮想Hub内部のゲートウェイ
$vpntarget = '10.0.0.1';

if ( ( @ARGV ne 1 ) and ( $ARGV[0] ne 'start' ) and ( $ARGV[0] ne 'stop' ) ) {
    print "Usage: $0 {start|stop}";
	exit(1);
}

$read = readpipe('route -n');

@lines = split(/\n/, $read);

foreach (@lines) {
    @match = /([0-9\.]+)[\s]+([0-9\.]+)[\s]+([0-9\.]+)[\s]+[A-Z]+[\s]+[0-9]+[\s]+[0-9]+[\s]+[0-9]+[\s]+([A-Za-z0-9_]+)/;
    if ( ( $match[0] eq '0.0.0.0' ) and ( $match[1] ne '10.0.0.1') and ( $match[2] eq '0.0.0.0' ) ) {
        $gateway = $match[1];
        $interface = $match[3];
    }
}


# They're too ugly... hmm...

if ( $ARGV[0] eq 'start' ) {
        system("$daemon start");
        system("ifdown $vpnif");
        system("$vpncmd localhost /client /CMD AccountConnect $conname");
        sleep(10);
        system("ifup $vpnif");
        system("route add -net $vpnnet netmask 255.255.0.0 gw $gateway metric 0 $interface");
        system("route add default gw $gateway netmask 0.0.0.0 metric 20 $interface");
        system("route del default gw $gateway netmask 0.0.0.0 metric 0 $interface");
        system("route add default gw $vpntarget netmask 0.0.0.0 metric 0 $vpnif");
}

if ( $ARGV[0] eq 'stop' ) {
        system("route del default gw $vpntarget netmask 0.0.0.0 metric 0 $vpnif");
        system("route del -net $vpnnet netmask 255.255.0.0 gw $gateway metric 0 $interface");
        system("route add default gw $gateway netmask 0.0.0.0 metric 0 $interface");
        system("route del default gw $gateway netmask 0.0.0.0 metric 20 $interface");
        system("ifdown $vpnif");
        system("$vpncmd localhost /client /CMD AccountDisconnect $conname");
        system("$daemon stop");
}

exit(0);
