<?php

use app\CliUtil as cli;

require_once __DIR__.'/../src/init.php';

function usage(string $msg = ''): never  {
    if ($msg !== '')
        fwrite(STDERR, "error: {$msg}\n");
    $script = $GLOBALS['argv'][0];
    fwrite(STDERR, "usage: {$script} --input-file FILE --issue ISSUE --year YEAR\n");
    exit(1);
}

function pdftotext(string $file_path): string {
    $output = [];
    $code  = 0;
    exec("pdftotext -layout -enc UTF-8 ".escapeshellarg($file_path)." -", $output, $code);
    if ($code !== 0)
        throw new \RuntimeException("pdftotext failed (code {$code})");
    return implode("\n", $output);
}


$input_file = null;
$issue = null;
$year = null;
for ($i = 1; $i < $argc; $i++) {
    switch ($argv[$i]) {
        case '--input-file':
            $input_file = $argv[++$i] ?? usage('missing value for --input-file');
            break;

        case '--issue':
            $issue = $argv[++$i] ?? usage('missing value for --issue');
            break;

        case '--year':
            $year = $argv[++$i] ?? usage('missing value for --year');
            break;

        default:
            usage("unknown option {$argv[$i]}");
    }
}

if (is_null($input_file) || is_null($issue) || is_null($year))
    usage();

if (!file_exists($input_file))
    cli::die($input_file.': file not found');

if (strtolower(extension($input_file)) != 'pdf')
    cli::die('only PDF files are accepted');

exec('command -v pdftotext', $tmp, $code);
if ($code !== 0)
    cli::die('pdftotext command not found');

try {
    $text = pdftotext($input_file);
} catch (RuntimeException $e) {
    cli::die($e->getMessage());
}

$dst = '/usr/local/www/4in1-files/Baconiana/'.basename($input_file);
if (!copy($input_file, $dst))
    cli::die('failed to copy file to '.$dst);

$size = filesize($dst);
$id = \app\foreignone\files\BaconianaIssue::add('Baconiana/'.basename($input_file), $size, $issue, (int)$year, $text);
if (!$id)
    cli::die('error, check the logs');

echo "id = $id\n";