#!/usr/bin/php -q
<?php
error_reporting(1);

//Include PEAR DB
include_once('DB.php');

//Get our database information right from FreePBX and attempt to connect
$amp_conf = getconf((isset($_ENV['FREEPBXCONFIG']) && strlen($_ENV['FREEPBXCONFIG']))?$_ENV['FREEPBXCONFIG']:'/etc/amportal.conf');
if (!isset($db)) {
	$db = DB::connect('mysql://'.$amp_conf['AMPDBUSER'].':'.$amp_conf['AMPDBPASS'].'@'.$amp_conf['AMPDBHOST'].'/'.$amp_conf['AMPDBNAME']); // attempt connection
}

//get email addresses
$ret = $db->getAll('SELECT * FROM sysadmin_options WHERE `key` IN("update_cronstate", "update_hour", "update_minute", "update_month", "update_day", "update_weekday")', DB_FETCHMODE_ASSOC);
if($db->IsError($ret)) {
	die($ret->getDebugInfo()."\n".$ret->getUserInfo()."\n".$db->last_query);
}

foreach ($ret as $r) {
	switch ($r['key']) {
		case 'update_cronstate':
			if ($r['value'] == 'never') {
				$cron = '';
				break 2;
			} else {
				$cron['command'] = '/usr/sbin/sysadmin_update_system -a > /dev/null 2>&1';
				break;
			}
		case 'update_hour':
			$cron['hour'] = $r['value'];
			break;
		case 'update_minute':
			$cron['minute'] =  $r['value'];
			break;
		case 'update_month':
			$cron['month'] =  $r['value'];
			break;
		case 'update_day':
			$cron['dom'] =  $r['value'];
			break;
		case 'update_weekday':
			$cron['dow'] =  $r['value'];
			break;
	}
}


$set = edit_crontab('/usr/sbin/sysadmin_update_system', $cron);
if ($set) {
	echo 'Update cron set!';
} else {
	echo 'Update cron failed';
}

//Function to get our FreePBX Configuration Options
function getconf($filename) {
  $file = file($filename);
  foreach($file as $line => $cont){
  	if(substr($cont,0,1)!='#'){
  		$d=explode('=',$cont);
  		if(isset($d['0'])&& isset($d['1'])){$conf[trim($d['0'])]=trim($d['1']);}
  	}
  }
  return $conf;
}
/**
 * function edit crontab
 * short Add/removes stuff rom conrtab
 * long Use this function to programmatically add/remove data from the crontab
 * will always run as the asterisk user
 *
 * @pram string
 * @pram mixed
 * @returns bool
 */

function edit_crontab($remove = '', $add = '') {
	$cron_out = array();
	$cron_add = false;

	//get all crontabs
	$exec = '/usr/bin/crontab -l ' . $cron_user;
	exec($exec, $cron_out, $ret);

	//make sure the command was executed successfully before continuing
	if ($ret > 0) {
		return false;
	}

	//remove anythign that nteeds to be removed
	foreach ($cron_out as $my => $c) {
		//ignore comments
		if (substr($c, 0, 1) == '#') {
			continue;
		}

		//remove blank lines
		if (!$c) {
			unset($cron_out[$my]);
		}

		//remove $remove
		if ($remove) {
			if (strpos($c, $remove)) {
				unset($cron_out[$my]);
			}
		}
	}

	//if we have $add and its an array, parse it & fill in the missing options
	//if its a string, add it as is
	if($add) {
		if (is_array($add)) {
			if (isset($add['command'])) {
				$cron_add['minute']		= isset($add['minute'])	? $add['minute']	: '*';
				$cron_add['hour']		= isset($add['hour'])	? $add['hour']		: '*';
				$cron_add['dom']		= isset($add['dom'])	? $add['dom']		: '*';
				$cron_add['month']		= isset($add['month'])	? $add['month']		: '*';
				$cron_add['dow']		= isset($add['dow'])	? $add['dow']		: '*';
				$cron_add['command']	= $add['command'];
				$cron_add = implode(' ', $cron_add);
			} else {
				//no command? No cron!
				$cron_add = '';
			}
		} else {
			//no array? Just use the string
			$cron_add = $add;
		}
	}

	//if we have soemthing to add
	if ($cron_add) {
		$cron_out[] = $cron_add;
	}

	//write out crontab
	$exec = '/bin/echo "' . implode("\n", $cron_out) . '" | /usr/bin/crontab ' . $cron_user . '-';
	exec($exec, $out_arr, $ret);

	return ($ret > 0 ? false : true);
}
?>
