#!/usr/bin/php -q
<?php
//load license
require_once(dirname(__FILE__) . '/../lib/sysadmin/license_loader.php');
require_once(dirname(__FILE__) . '/../lib/sysadmin/licensed.php');

//if we dont have a valid license file installed, we wont be able to load sysadmin_get_license(),
//so return something usefull here
if (!function_exists('sysadmin_get_license')) {
	function sysadmin_get_license() {
		return false;
	}
}

$opts = getopt('d');

$lic = sysadmin_get_license();
if (!$lic) {
	echo "License file not found or invalid license! \n";
	exit(1);
}

//d = download cert files
if (isset($opts['d'])) {
	$dir		= '/etc/openvpn/deploymentvpn/';
	$conf		= '/etc/openvpn/' . $lic['deploymentid'] . '.conf';
	$crt		= $dir . $lic['deploymentid'] . '.crt';
	$key		= $dir . $lic['deploymentid'] . '.key';
	$ca			= $dir . 'ca.crt';
	
	//create the directory if its missing
	if (!is_dir($dir)) {
		mkdir($dir, 0755, true);
	}
	
	//download files from ftp server
	$server		= 'backup1.schmoozecom.net';
	$ftp		= ftp_connect($server);
	$ftp_auth	= ftp_login($ftp, $lic['backup_username'], $lic['backup_password']);
	ftp_pasv($ftp, true);
	ftp_get($ftp,  $conf, $lic['deploymentid'] . '.conf', FTP_BINARY);
	ftp_get($ftp,  $crt, $lic['deploymentid'] . '.crt', FTP_BINARY);
	ftp_get($ftp,  $key, $lic['deploymentid'] . '.key', FTP_BINARY);
	ftp_get($ftp,  $ca, 'ca.crt', FTP_BINARY);
	ftp_close($ftp);

	//crash & burn if we couldnt get the files we need
	if (!file_exists($conf) || !file_exists($crt) || !file_exists($key) || !file_exists($ca)) {
		echo 'Could not download files, aborting!' . PHP_EOL;
		exit(1); 
	}
}

if ($lic && isset($lic['vpn_ip'])) {
	exec('/etc/init.d/openvpn restart');
	sleep(10);
	exec('route add 10.4.2.6 gw ' . $lic['vpn_ip']);
}

?>