#!/usr/bin/env php
<?php
// vim: :set filetype=php tabstop=4 shiftwidth=4 autoindent smartindent:

require '/usr/lib/sysadmin/includes.php';
$restrict_mods  = array('firewall' => true);
$g 		= new \Sysadmin\GPG();
$sigfile	= __DIR__."/../module.sig";
$cfg		= \Sysadmin\FreePBX::Config();
$astspooldir	= $cfg->get('ASTSPOOLDIR');
$astlogdir	= '/var/log/asterisk';//$cfg->get('ASTLOGDIR');
$logfile 	= $astlogdir."/firewall.log";
$webuser 	= 'asterisk';//$cfg->get('AMPASTERISKWEBUSER');
$webgroup 	= 'asterisk'; //$cfg->get("AMPASTERISKWEBGROUP");
try {
	$sig = $g->checkSig($sigfile);
	if (!isset($sig['config']['hash']) || $sig['config']['hash'] !== "sha256") {
		throw new \Exception("Invalid sig file.. Hash is not sha256 - check $sigfile");
	}

	// Check the hash of the validator, before we include it
	if (empty($sig['hashes']['hooks/voipfirewalld'])) {
		throw new \Exception("Firewalld not part of module.sig");
	}

	$fd = __DIR__."/voipfirewalld";

	$fhash = hash_file('sha256', $fd);
	if ($fhash !== $sig['hashes']['hooks/voipfirewalld']) {
		throw new \Exception("Firewalld tampered");
	}
} catch (\Exception $e) {
	print "Error: ".$e->getMessage().". Sleeping for 10 seconds and retrying start.\n";
	sleep(10);
	touch($astspooldir."/incron/firewall.firewall");
	exit;
}

// Start the daemon
chmod($fd, 0755);
exec("nohup $fd >> ".$logfile." 2>&1 &");
chown($logfile, $webuser);
chgrp($logfile, $webgroup);
