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

define('CIGAR_VERSION', '1.12.3');
$start = microtime(true);

foreach (['/../../..', '/../..', '/../vendor', '/vendor'] as $autoloadFileDirectory) {
    if (file_exists(__DIR__ . $autoloadFileDirectory . '/autoload.php')) {
        require __DIR__ . $autoloadFileDirectory . '/autoload.php';
        break;
    }
}

use Brunty\Cigar\AsyncChecker;
use Brunty\Cigar\EchoWriter;
use Brunty\Cigar\JsonWriter;
use Brunty\Cigar\Outputter;
use Brunty\Cigar\Parser;
use Brunty\Cigar\Result;

$options = getopt('c:ia:u:jh:t:s:', ['version', 'help', 'quiet', 'config:', 'insecure', 'auth:', 'url:', 'json', 'header:', 'timeout:', 'connect-timeout:']);

if (isset($options['help'])) {
    $content = <<<HELP

\033[33mUsage:\033[0m
  cigar [options]


\033[33mOptions:\033[0m
      \033[32m-c file.json, --config=file.json\033[0m         Use the specified config file instead of the default .cigar.json file 
      \033[32m-u URL,       --url=URL\033[0m                  Base URL for checks, e.g. https://example.org/
      \033[32m-i,           --insecure\033[0m                 Allow invalid SSL certificates
      \033[32m-a,           --auth\033[0m                     Authorization header "\074type\076 \074credentials\076"
      \033[32m-h,           --header\033[0m                   Custom header "\074name\076: \074value\076"
      \033[32m-s            --connect-timeout=TIMEOUT\033[0m  Connect Timeout
      \033[32m-t,           --timeout=TIMEOUT\033[0m          Timeout
      \033[32m-j,           --json\033[0m                     Output JSON
      \033[32m              --quiet\033[0m                    Do not output any message
      \033[32m              --version\033[0m                  Print the version of Cigar 

Created by Matt Brunt
E: matt@mfyu.co.uk
T: twitter.com/Brunty
G: github.com/brunty/cigar

HELP;
    echo $content;
    exit(0);
}

if (isset($options['version'])) {
    $version = CIGAR_VERSION;
    $content = <<<VERSION
  ____ ___ ____    _    ____  
 / ___|_ _/ ___|  / \  |  _ \ 
| |    | | |  _  / _ \ | |_) |
| |___ | | |_| |/ ___ \|  _ < 
 \____|___\____/_/   \_\_| \_\

\033[0;90;49mThe simple smoke testing tool.\033[0m
 
Version \033[36m{$version}\033[0m

For additional help use \033[36m--help\033[0m


VERSION;
    echo $content;
    exit(0);
}

$writer = isset($options['j']) || isset($options['json']) ? new JsonWriter() : new EchoWriter();
$outputter = new Outputter(isset($options['quiet']), $writer);

$file = $options['c'] ?? ($options['config'] ?? '.cigar.json');
$baseUrl = $options['u'] ?? ($options['url'] ?? null);

if ( ! file_exists($file)) {
    $outputter->writeErrorLine('Could not find configuration file: ' . $file);
    exit(1);
}

$secure = ! (isset($options['i']) || isset($options['insecure']));
$authorization = $options['a'] ?? $options['auth'] ?? null;
$headers = (array) ($options['h'] ?? $options['header'] ?? []);
$connectTimeout = $options['s'] ?? $options['connect-timeout'] ?? null;
$timeout = $options['t'] ?? $options['timeout'] ?? null;

try {
    $domains = (new Parser($baseUrl, $connectTimeout, $timeout))->parse($file);
} catch (\Throwable $e) {
    $outputter->writeErrorLine('Unable to parse .cigar.json file');
    exit(1);
}

$results = (new AsyncChecker($secure, $authorization, $headers))->check($domains);
$passedResults = array_filter($results, function (Result $result) {
    return $result->hasPassed();
});

$outputter->outputResults($passedResults, $results, $start);

if (count($passedResults) !== count($results)) {
    exit(1);
}

exit(0);
