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

/**
 * Lint ruleset XML file.
 */

use SebastianBergmann\Diff\Differ;
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;

const RULESET = 'src/Chiron/ruleset.xml';
const XML_SCHEMA = 'resources/XMLSchema.xsd';
const PHPCS_SCHEMA = 'vendor/squizlabs/php_codesniffer/phpcs.xsd';

// Change to the repository root.
chdir(realpath(dirname(__FILE__, 2)));

if (!is_readable(PHPCS_SCHEMA)) {
    echo "Unable to read phpcs.xsd; perhaps you forgot to run 'composer update'?\n";
    exit(1);
}

require_once 'vendor/autoload.php';

$printValidity = function (bool $isValid, string $filename): void {
    printf(
        'File: %s %s%s',
        $filename,
        $isValid ? 'validates.' : 'fails to validate.',
        PHP_EOL
    );
};

$phpcsSchemaContents = file_get_contents(PHPCS_SCHEMA);
$rulesetContents = file_get_contents(RULESET);

$phpcsSchema = new DOMDocument();
$phpcsSchema->loadXML($phpcsSchemaContents);
$isPhpcsSchemaValid = $phpcsSchema->schemaValidate(XML_SCHEMA);
$printValidity($isPhpcsSchemaValid, PHPCS_SCHEMA);

$ruleset = new DOMDocument();
$ruleset->loadXML($rulesetContents);
$isRulesetValid = $ruleset->schemaValidateSource($phpcsSchema->saveXML());
$printValidity($isRulesetValid, RULESET);

$builder = new UnifiedDiffOutputBuilder('', true);
$differ = new Differ($builder);
$diff = $differ->diff($rulesetContents, $ruleset->saveXML());
$hasDifferences = $diff !== '';

if ($hasDifferences) {
    printf(
        '%1$sI found the following issues with %2$s.%1$sYou may fix these issues automatically with:%1$s%1$s  composer lint:fix%1$s%1$s%3$s%1$s',
        PHP_EOL,
        RULESET,
        $diff
    );
}

exit($isPhpcsSchemaValid && $isRulesetValid && !$hasDifferences ? 0 : 1);
