#!/usr/local/bin/php

<?php
	# Which VPN to reset?
	$vpnname="set this";

	# PRINT THE DATE! :D
	print date("Y-m-d H:i:s") . "\n";

	# Preload
	require_once('service-utils.inc');
	require_once("ipsec.inc");

	# Init
	function fubar($reason) {print $reason . "\n"; exit(1);}
	$xml=simplexml_load_file("/cf/conf/config.xml") or fubar("Error: Cannot load config.xml");
	$found = false;

	# OpenVPN
	foreach($xml->openvpn->{'openvpn-client'} as $vpn) {
		$desc = html_entity_decode((string)$vpn->description);
		print "Found OpenVPN: $desc\n";
		if (strcasecmp($desc, $vpnname) != 0) continue;
		if ($found) print "Warning: Multiple matching VPN connections\n";
		$found = true;
		print "Restarting VPN with ID " . $vpn->vpnid . "\n";

		# code figured out from /etc/inc/service-utils.inc
		service_control_restart("openvpn", array('vpnmode' => 'client', 'id' => $vpn->vpnid));
	}

	# IPsec
	foreach($xml->ipsec->{'phase1'} as $vpn) {
		$desc = html_entity_decode((string)$vpn->descr);
		print "Found IPsec: $desc\n";
		if (strcasecmp($desc, $vpnname) != 0) continue;
		if ($found) print "Warning: Multiple matching VPN connections\n";
		$found = true;
		print "Restarting VPN with ID " . $vpn->ikeid . "\n";

		# code from /usr/local/www/status_ipsec.php ("ikedisconnect")
		$_GET = array(ikeid => $vpn->ikeid . "000"); # wtf is up with the zeroes?
		mwexec_bg("/usr/local/sbin/ipsec down con" . escapeshellarg($_GET['ikeid']));

		# code from /usr/local/www/status_ipsec.php ("connect")
		$_GET = array(ikeid => $vpn->ikeid);
		$ph1ent = ipsec_get_phase1($_GET['ikeid']);
		if (!empty($ph1ent)) {
			if (empty($ph1ent['iketype']) || $ph1ent['iketype'] == 'ikev1' || isset($ph1ent['splitconn'])) {
				$ph2entries = ipsec_get_number_of_phase2($_GET['ikeid']);
				for ($i = 0; $i < $ph2entries; $i++) {
					$connid = escapeshellarg("con{$_GET['ikeid']}00{$i}");
					mwexec_bg("/usr/local/sbin/ipsec down {$connid}");
					mwexec_bg("/usr/local/sbin/ipsec up {$connid}");
				}
			} else {
				mwexec_bg("/usr/local/sbin/ipsec down con" . escapeshellarg($_GET['ikeid']));
				mwexec_bg("/usr/local/sbin/ipsec up con" . escapeshellarg($_GET['ikeid']));
			}
		}
	}

	# The End
	if (!$found) fubar("Error: No VPN with the name '$vpnname'");
?>

