#!/usr/bin/env php
<?php

require_once('vendor/autoload.php');
require_once('utils.inc.php');

use PhpDevCommunity\DotEnv;
use League\CLImate\CLImate;

$climate = new CLImate();
$climate->description('yeswiki-updater, find and update YesWiki like a professionnal 🌈🦄');
$isRoot = (0 == posix_getuid());

if ($isRoot) {
    $absolutePathToEnvFile = __DIR__ . '/.env';
    if (file_exists($absolutePathToEnvFile)) {
        (new DotEnv($absolutePathToEnvFile))->load();
    } else {
        $climate->error('ERROR : No .env file found.');
        exit;
    }

    $climate->arguments->add([
      'path' => [
        'prefix'       => 'p',
        'longPrefix'   => 'path',
        'description'  => 'Path to scan for wikis',
        'required'     => true,
      ],
      'output' => [
        'prefix'       => 'o',
        'longPrefix'   => 'output',
        'description'  => 'Output results in table format, json or csv',
        'defaultValue' => 'table'
      ],
      'update' => [
        'prefix'       => 'u',
        'longPrefix'   => 'update',
        'description'  => 'Update to latest version of stable yeswiki',
        'noValue' => true
      ],
      'depth' => [
        'prefix'       => 'd',
        'longPrefix'   => 'depth',
        'description'  => 'Depth to scan folders for wikis',
        'defaultValue' => 1
      ],
    ]);
    try {
        $climate->arguments->parse();
    } catch (\Throwable $th) {
        if (!$climate->arguments->defined('path')) {
            $climate->error('This command needs a valid path argument for example : -p /var/www/html');
            $climate->usage();
            return;
        }
    }
    $path = $climate->arguments->get('path');
    if (!empty($path) && is_dir($path)) {
        try {
            $update = $climate->arguments->get('update');
            $output = $climate->arguments->get('output');
            $depth = $climate->arguments->get('depth');
            $matches = searchWikis($path, 'wakka.config.php', $depth);
            if (count($matches) == 0) {
                $climate->info('No yeswiki found on path ' . $path . ' with depth ' . $depth);
                exit;
            }
            if (count($matches) > 0 && $update) { // update yeswiki list
                $climate->info('Update yeswiki');
                $tmpFile = '/tmp/yeswiki.zip';
                $destDir = '/tmp/yeswiki_for_update';
                exec('rm -rf ' . $destDir . ' && mkdir -p ' . $destDir, $output);
                if (file_exists($tmpFile)) {
                    unlink($tmpFile);
                }
                exec('curl --insecure -s -o ' . $tmpFile . ' ' . $_SERVER['source_archive_url']);
                exec('unzip ' . $tmpFile . ' "doryphore/*" -d ' . $destDir);
                exec('mv ' . $destDir . '/doryphore/* ' . $destDir . '/');
                exec('rm -rf ' . $destDir . '/doryphore');
                unlink($tmpFile);
                foreach ($matches as $k => $wiki) {
                    $climate->info(upgradeWiki($destDir, $wiki['PATH']));
                }
            } else { // show yeswiki list info
                $climate->info(count($matches) . ' yeswikis found on ' . $path);
                switch ($output) {

                    case 'table':
                        $climate->table($matches);
                        break;

                    case 'json':
                        $climate->json($matches);
                        break;

                    case 'csv':
                        $fileName = 'yeswiki-list.csv';
                        $file = fopen($fileName, "w");
                        foreach ($matches as $line) {
                            fputcsv($file, $line);
                        }
                        $climate->info($fileName . ' was created.');
                        break;
                }
            }
        } catch (Exception $e) {
            $climate->error('ERROR : ' . $e->getMessage());
        }
    } else {
        $climate->usage();
    }
} else {
    $climate->error('ERROR : this script needs root privilege to run.');
    exit;
}