#!/usr/bin/php -q
<?php
$usage = <<<EOF

Process package files in NerdPack config. Download and install,
delete and uninstall, based on the config value and [options].

Usage: packagemanager [options]

  -d, --download   download missing packages selected
  -r, --delete     delete packages not selected
  -q, --quiet      supress all packages progress
  -u, --uninstall  uninstall packages not selected
  -v, --verbose    print all packages progress
      --help       display this help and exit
      --version    output version information and exit


EOF;

$shortopts = "drquv";
$longopts = [
	"delete",
	"download",
	"help",
	"quiet",
	"uninstall",
	"verbose",
	"version"
];
$args = getopt($shortopts, $longopts);

if (array_key_exists("help", $args)) {
	echo $usage;
	exit(1);
}

if (array_key_exists("version", $args)) {
	echo "Package Manager Version: 1.2\n";
	exit(1);
}

$argd = (array_key_exists("d", $args) || array_key_exists("download", $args));
$argq = (array_key_exists("q", $args) || array_key_exists("quiet", $args));
$argr = (array_key_exists("r", $args) || array_key_exists("delete", $args));
$argu = (array_key_exists("u", $args) || array_key_exists("uninstall", $args));
$argv = (array_key_exists("v", $args) || array_key_exists("verbose", $args));

require_once '/usr/local/emhttp/plugins/NerdPack/include/NerdPackHelpers.php';
require_once '/usr/local/emhttp/plugins/NerdPack/include/DownloadHelpers.php';

logger('Processing Packages...');

foreach ($pkg_cfg as $pkg_name => $pkg_pref) { // get preferences for each package
	$pkg_cmd = '';
	$pkg_name = str_replace('_', '.', $pkg_name); // replace "_" with "." in package names
	$pkg_pattern = '/^'.$pkg_name.'.*/'; // search pattern for packages
	$pkg_install_status = preg_grep($pkg_pattern, $pkgs_installed); // check install status
	$pkg_download_status = preg_grep($pkg_pattern, $pkgs_downloaded); // check package download status
	
	//check if plugin is dependent on package
	$plugins = [];
	exec("cd /boot/config/plugins ; find *.plg | xargs grep '$pkg_name' -sl",$plugins);
	if ($plugins){
		$plg_msg = "$pkg_name used by plugin: ";
		foreach ($plugins as $plugin){
			$plg_msg .= pathinfo($plugin, PATHINFO_FILENAME).", ";
			}
			logger(substr($plg_msg, 0, -2));
	}

	if ($pkg_pref == 'yes') {
		// if executing from the wegui check status and download if necessary
		if ($argd) {
			if (!$pkg_download_status) {

				$pkg_online_status = preg_grep($pkg_pattern, $pkgs_github_array);

				$pkg_matches = array_filter($pkgs_github_array, function($a) use ($pkg_pattern) {
					return preg_grep($pkg_pattern, $a);
				});

				$pkg_gitname = array_values($pkg_matches)[0]['name'];
				$pkg_file = $pkg_path.$pkg_gitname;
				$pkg_url = array_values($pkg_matches)[0]['download_url'];
				$pkg_sha1 = array_values($pkg_matches)[0]['sha'];

				logger('Downloading '.$pkg_gitname.' package...', $argq);

				get_file_from_url($pkg_file, $pkg_url);

				if (file_check_sha1($pkg_file, $pkg_sha1))
					logger($pkg_gitname.' package downloaded sucessfully!', $argq);
				else{
					if(is_file($pkg_file))
						unlink($pkg_file);
					logger($pkg_gitname.' package download failed!', $argq);
				}
			}
		}
		if (!$pkg_install_status) {
			$pkg_msg = 'Installing';
			$pkg_cmd = 'upgradepkg --install-new '.$pkg_path.$pkg_name.'* 2>&1';
		}
	} else if ($pkg_pref == 'no' && $pkg_install_status && $argu) {
		if($plugins){
			logger("Unable to uninstall $pkg_name",$argq);
			}else{
		 $pkg_msg = 'Uninstalling';
		 $pkg_cmd = 'removepkg '.$pkg_path.$pkg_name.'* 2>&1';
	 	if ($argr) {
 			$pkg_cmd .= '; rm '.$pkg_path.$pkg_name.'* 2>&1';
		 	$pkg_msg .= ' and deleting';
		}
		}
	}
	if (!empty($pkg_cmd)) {
		logger("$pkg_msg $pkg_name package...");
		shell_exec($pkg_cmd);
		//$output = shell_exec($pkg_cmd);
		//logger($output);
	} else {
		if ($pkg_pref == 'yes')
		 logger("$pkg_name package up to date", $argq);
		 }
}

logger('All packages processed...');
?>