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

declare(strict_types=1);

foreach([// janitor from zip with vendor
         __DIR__ . '/vendor/autoload.php',
         // janitor from composer in site/plugins/kirby3-janitor
         realpath(__DIR__ . '/../../../') . '/vendor/autoload.php',
        ] as $file) {
    if (file_exists($file)) {
        require $file;
        break;
    }
}

ini_set('display_errors', '1');

$climate = new \League\CLImate\CLImate();

$climate->arguments->add([
    'help' => [
        'prefix' => 'h',
        'longPrefix' => 'help',
        'description' => 'Display the help',
        'noValue' => true,
    ],
    'list' => [
        'prefix' => 'l',
        'longPrefix' => 'list',
        'description' => 'List all registered jobs',
        'noValue' => true,
    ],
    'format' => [
        'prefix' => 'f',
        'longPrefix' => 'format',
        'description' => 'Format the output as "label", "table" or "json"',
        'defaultValue' => 'label',
    ],
    'kirby' => [
        'prefix' => 'k',
        'longPrefix' => 'kirby',
        'description' => 'Relative path to Kirbys public folder',
        'defaultValue' => '/',
    ],
    'verbose' => [
        'prefix' => 'v',
        'longPrefix' => 'verbose',
        'description' => 'Show debug info',
        'noValue' => true,
    ],
    'job' => [
        'description' => 'Run a job',
    ],
    'quiet' => [
        'prefix' => 'q',
        'longPrefix' => 'quiet',
        'description' => 'Run jobs silently',
        'noValue' => true,
    ],
    'tinker' => [
        'prefix' => 't',
        'longPrefix' => 'tinker',
        'description' => 'Run a REPL session',
        'noValue' => true,
    ],
    'down' => [
        'prefix' => 'd',
        'longPrefix' => 'down',
        'description' => 'Start maintenance mode',
        'noValue' => true,
    ],
    'up' => [
        'prefix' => 'u',
        'longPrefix' => 'up',
        'description' => 'Stop maintenance mode',
        'noValue' => true,
    ],
]);
$climate->arguments->parse();
$verbose = $climate->arguments->defined('verbose');

// COMMAND: kirby
$kirbyPublicFolder = null;
foreach([   // site/plugins/kirby3-janitor => /index.php
            realpath(__DIR__ . '/../../../'),
            // site/plugins/kirby3-janitor => /public/index.php
            realpath(__DIR__ . '/../../../public'),
        ] as $dir) {
    if ($dir !== false && file_exists($dir . '/index.php')) {
        $kirbyPublicFolder = $dir;
        break;
    }
}
if ($climate->arguments->defined('kirby')) {
    $kirbyPublicFolder = realpath(__DIR__ . DIRECTORY_SEPARATOR . ltrim($climate->arguments->get('kirby'), DIRECTORY_SEPARATOR));
}
if ($kirbyPublicFolder) {
    $kirbyLoader = $kirbyPublicFolder . DIRECTORY_SEPARATOR . 'janitor-' . sha1(__DIR__) . '.php';
    if (! file_exists($kirbyLoader)) {
        file_put_contents(
            $kirbyLoader,
            str_replace('echo ', '// echo ',
                file_get_contents($kirbyPublicFolder . DIRECTORY_SEPARATOR . 'index.php')
            )
        );
        if ($verbose) {
            $climate->backgroundYellow()->out('ATTENTION! Janitor created this file to load the Kirby instance: ' . $kirbyLoader);
        }
    }
    include $kirbyLoader;
    if ($verbose) {
        $climate->backgroundCyan()->out('Using Kirby instance from: ' . $kirbyLoader);
    }
}

\Bnomei\Janitor::climate($climate);
$janitor = new \Bnomei\Janitor();

// COMMAND: help
$command = $climate->arguments->defined('help');
if ($command) {
    $climate->usage();
}

// COMMAND: list
$command = $climate->arguments->defined('list');
if ($command) {
    foreach ($janitor->listJobs() as $key) {
        $climate->out($key);
    }
}

// COMMAND: quiet
$command = $climate->arguments->get('quiet');
if ($command) {
    $climate->output->add('quiet', new \Bnomei\QuietWriter());
    $climate->output->defaultTo('quiet');
}

// COMMAND: tinker
$command = $climate->arguments->get('tinker');
if ($command) {
    while (true) eval($climate->input('>>> ')->prompt());
}

// COMMAND: down
$command = $climate->arguments->get('down');
if ($command) {
    file_put_contents(kirby()->roots()->index() . '/down', date('c'));
}

// COMMAND: up
$command = $climate->arguments->get('up');
if ($command) {
    $down = kirby()->roots()->index() . '/down';
    if (file_exists($down)) {
        unlink($down);
    }
}

// COMMAND: job
$job = $climate->arguments->get('job');
if ($job) {
    $format = $climate->arguments->get('format');
    if ($format === 'class') {
        $janitor->job($job, [], $climate);
    } elseif ($format === 'json') {
        $climate->json($janitor->job($job));
    } elseif ($format === 'table') {
        $table = [];
        foreach ($janitor->job($job) as $key => $value) {
            $table[] = [$key, $value];
        }
        $climate->table($table);
    } else {
        $data = $janitor->job($job);
        $status = $data['status'];
        $label = array_key_exists('label', $data) ? $data['label'] : $status;
        if ($status === 200) {
            $climate->lightGreen($label);
        } elseif ($status === 204) {
            $climate->lightRed($label);
        } elseif ($status === 404) {
            $climate->backgroundRed($label);
        } else {
            $climate->out($label);
        }
    }
}
