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

/**
 * @file
 * Offline file audit, usable before the module or Drupal site is installed.
 */

use Drupal\key_audit\ConfigAuditor;
use Drupal\key_audit\FileScanner;
use Drupal\key_audit\Report;

require dirname(__DIR__) . '/bootstrap.php';

$options = ['format' => 'text', 'fail-on' => 'high', 'project-root' => NULL, 'web-root' => NULL];
try {
  foreach (array_slice($argv, 1) as $argument) {
    if ($argument === '--help') {
      fwrite(STDOUT, "Usage: key-audit --path=PATH [--project-root=/absolute/root] [--web-root=/absolute/root/web] [--format=text|json] [--fail-on=high]\nExit: 0 below threshold; 1 findings; 2 incomplete/error. No site bootstrap or key resolution.\n");
      exit(0);
    }
    if (!preg_match('/^--(path|project-root|web-root|format|fail-on)=(.+)$/s', $argument, $match)) {
      throw new InvalidArgumentException('Invalid option.');
    }
    $options[$match[1]] = $match[2];
  }
  if (!isset($options['path']) || !in_array($options['format'], ['text', 'json'], TRUE)) {
    throw new InvalidArgumentException('Missing path or invalid format.');
  }
  // Validate the threshold before opening any files.
  (new Report('validation'))->exitCode($options['fail-on']);
  $report = (new FileScanner(new ConfigAuditor()))->scan($options['path'], $options['project-root'], $options['web-root']);
  fwrite(STDOUT, $report->render($options['format'], $options['fail-on']));
  exit($report->exitCode($options['fail-on']));
}
catch (Throwable) {
  // Never echo argv, parser diagnostics or exception messages with secret data.
  fwrite(STDERR, "Key Audit could not complete. Check --help, local paths and dependencies. Error details suppressed.\n");
  exit(2);
}
