#!/usr/bin/php
<?php
/**
 * run
 *
 * application cli bootstrap ;)
 * php pattern: front controler 
 *
 * to find out if CLI is used, try constant PHP_SAPI for value 'cli'
 */
$sessionid = false;

function getCliApps($basedir, $baseapp = '', $result = array()) {
	if(!$dir = opendir($basedir)) {
		return $result;
	}
	while (($file = readdir($dir)) !== false) {
		if($file == '.' || $file == '..') {
			continue;
		}
		$nextapp = $baseapp.($baseapp==''?'':'.');
		if(is_dir($basedir.'/'.$file)) {
			$result = array_merge($result, getCliApps($basedir.'/'.$file, $nextapp.$file, $result));
		} else {
			if($file == 'app.php' || $file == 'app.inc') {
				$result[$baseapp] = $basedir.'/'.$file;
			} elseif (preg_match('%^([^\.]+)\.(php|inc)$%i',$file,$f)) {
				$result[$nextapp.$f[1]] = $basedir.'/'.$file;
			}
		}
	}
	return $result;
}

if($argc < 2) {
	echo("command line interface\r\n--------------------------------------\r\n");
	echo('usage: '.$argv[0]." {app} [{param}]\r\n\r\navailable apps:\r\n");

	foreach(getCliApps('/srv/pvr/fw/cli') as $iapp=>$ifile) {
		echo("\t$iapp\r\n");
	}
	return;
}
/**
 * get appname & other values from argument list
 */
$application = $argv[1];
$_SERVER['CLI'] = Array();
if($argc > 2) {
	for($i=2;$i<$argc;$i++) {
		if(stristr($argv[$i],'=')) {
			$delim = strpos($argv[$i],'=');
			$_SERVER['CLI'][substr($argv[$i],0,$delim)] = substr($argv[$i],$delim+1);
		} else {
			$_SERVER['CLI'][$i-2] = $argv[$i];
		}
	}
}
/**
 * include the main framework
 */
$fwcwd = getcwd();
chdir('/srv/pvr/fw');
require '/srv/pvr/fw/fw.inc';
chdir($fwcwd);

