<?php

	function setup_signalhandler()
	{
		declare(ticks = 1);
		pcntl_signal(SIGTERM, "signal_handler");
		pcntl_signal(SIGINT, "signal_handler");
	}

	function signal_handler($signal)
	{
		global $chkfile, $sql;

		if (function_exists(conlog))
			conlog("received ".$signal);

		if (isset($chkfile) && file_exists($chkfile))
		{
			if (function_exists(conlog))
				conlog("cleaning up ".$chkfile);
			unlink($chkfile);
		}
		die();
	}

	function conlog($message)
	{
		echo date('d-m-Y H:i:s')." ".$message."\n";
	}

	function chkprog($pd=false)
	{
		global $argv, $chkfile, $progdesc;
		$progdesc = $pd;
		$progname = basename($argv[0]);
		$chkfile = sys_get_temp_dir().'/'.$progname.'.run';
		if (file_exists($chkfile))
		{
			if ($pd)
				conlog($progdesc." already running. If this is incorrect remove ".$chkfile);
			exit;
		}
		if ($pd)
			conlog("Starting ".$progdesc);
		file_put_contents($chkfile, getmypid());
	}

	function endprog()
	{
		global $chkfile, $progdesc;
		db_close();
		if ($progdesc)
			conlog($progdesc." finished");
		if (file_exists($chkfile))
			unlink($chkfile);
		exit;
	}

	$cur = 1;
	function progress($lines, $found, $title=false)
	{
		global $cur;
		printf("\r%s Processing".($title ? ' '.$title:'').": %6.2f%% (%s/%s) %s found (%6.2f%%)", date('d-m-Y H:i:s'), ($cur/$lines)*100, $cur, $lines, $found, ($found/$lines)*100);
		$cur++;
	}
?>
