#!/usr/bin/php -q
<?php
$debug = FALSE;
$prog  = pathinfo(__FILE__, PATHINFO_FILENAME);
$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
      --debug      turn on debugging

EOF;

$shortopts = "dquv";
$longopts = [
    "debug",
    "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));
$argu = (array_key_exists("u", $args) || array_key_exists("uninstall", $args));
$argv = (array_key_exists("v", $args) || array_key_exists("verbose", $args));
$debug = array_key_exists("debug", $args);

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

/* debug */
function debug($m){
  global $prog, $debug;
  if($debug){
    $STDERR = fopen('php://stderr', 'w+');
    fwrite($STDERR, $m.PHP_EOL);
    fclose($STDERR);
  }
}

logger('Processing Packages...');

$pkg_find = '';

foreach ($pkg_cfg as $pkg_name => $pkg_pref) { // get preferences for each package
    $pkg_cmd = '';
    $pkg_msg = '';
    $pkg_name    = str_replace('_', '.', $pkg_name); // replace "_" with "." in package names
    $pkg_pattern = '/^'.$pkg_name.'.-*/'; // search pattern for packages
    $pkg_install_status  = !empty(preg_grep($pkg_pattern, $pkgs_installed)); // check install status
    $pkg_download_status = !empty(preg_grep($pkg_pattern, $pkgs_downloaded)); // check package download status
    $pkg_online_status   = !empty(preg_grep($pkg_pattern, $pkgs_github_array));
    $pkg_find .= " ! -name '".$pkg_name."*'";

    $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_extra_path.$pkg_gitname;
    $pkg_url     = array_values($pkg_matches)[0]['download_url'];
    $pkg_sha1    = array_values($pkg_matches)[0]['sha'];

    //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 package is selected to be installed
    if ($pkg_pref == 'yes') {
        // if executing from the wegui check status and download if necessary
        if ($argd) {
            if (!$pkg_download_status) { //if package is not downloaded

                //logger('Downloading '.$pkg_gitname.' package...', $argq);
                //logger('Downloading pkg_file '.$pkg_file.' package...', $argq);
                //logger('Downloading pkg_url '.$pkg_url.' package...', $argq);
                //logger('Downloading pkg_sha1 '.$pkg_sha1.' package...', $argq);

                get_file_from_url($pkg_file, $pkg_url);

                if (file_check_sha1($pkg_file, $pkg_sha1)){
                    logger($pkg_gitname.' package download sucessful!', $argq);
                }else{
                    if (file_exists($pkg_file))
                        unlink($pkg_file);
                    logger($pkg_gitname.' package download failed!', $argq);
                }
            }
        }

        if (!$pkg_install_status) { // if package is not installed
            $pkg_msg = 'Installing';
            $pkg_cmd = 'upgradepkg --install-new '.$pkg_extra_path.$pkg_name.'* 2>&1';
        }

    } elseif ($pkg_pref == 'no' && $pkg_download_status && $argu) {
        if($plugins){
            logger("$pkg_name in use by another plugin, not uninstalled.",$argq);
        }else{
            $pkg_msg = 'Uninstalling and deleting';
            $pkg_cmd = 'removepkg '.$pkg_extra_path.$pkg_name.'* 2>&1; rm '.$pkg_extra_path.$pkg_name.'* 2>&1';
        }
    }

    if (!empty($pkg_cmd)) {
        logger("$pkg_msg $pkg_name package...");
        shell_exec($pkg_cmd);
    }else{
        if ($pkg_pref == 'yes'){
            if (file_exists($pkg_file)){
                if (file_check_sha1($pkg_file, $pkg_sha1)){
                    $pkg_msg = 'package up to date, checksum ok.';
                }else{
                    if(!is_dir($pkg_file))
                        unlink($pkg_file);
                    $pkg_msg = 'checksum failed! package deleted.';
                }
            }else{
                $pkg_msg = ' package missing!';
            }

            logger($pkg_name." $pkg_msg", $argq);
        }
    }
}
logger('Cleaning up packages...');

$cmd = "find ".$pkg_extra_path." -type f ! -name 'packages.json' ! -name 'packages-desc'".$pkg_find." -delete 2>&1";
shell_exec($cmd);

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

/* print variable */
$defined_vars = get_defined_vars();

//remove vars from array to save
unset($defined_vars['pkgs_desc_array'],$defined_vars['pkgs_github_array']);

foreach (array("_GET","_POST","_COOKIE","_FILES","argv","argc","_SERVER") as $i)
    unset($defined_vars[$i]);

debug("\nDECLARED VARIABLES:\n".print_r($defined_vars, true));
unset($defined_vars);
?>