#!/usr/local/interworx/bin/php
<?php

/*
 * Installs the patched license files for this server's InterWorx version.
 *
 * Reporting never goes through log.pex: it checks the license before it logs anything, so it
 * fails on exactly the servers this package has not (yet) fixed. Every run instead writes
 * STATUS_FILE (JSON, for rollout tooling) and a syslog line (tag "interworx-internal-license").
 */

const STATUS_FILE = '/usr/local/interworx/etc/internal-license/status';
const LOG_TAG     = 'interworx-internal-license';

$iworx   = '/usr/local/interworx';
$pkg_dir = "{$iworx}/etc/internal-license";

// See src/variants.php for the layout and why ranges are by version, not build.
$files = require "{$pkg_dir}/src/variants.php";

$release = trim((string) @file_get_contents("{$iworx}/etc/env/release"));
if (!preg_match('/(?<version>[0-9]+\.[0-9]+\.[0-9]+)-[0-9]{4,}/', $release, $matches)) {
    skip($release, "Could not read a version from {$iworx}/etc/env/release; nothing changed");
}
$version = $matches['version'];

// Work out every file first, so an unsupported build changes nothing at all.
$plan = [];
foreach ($files as $file => $variants) {
    $variant = pickVariant($variants, $version);
    if ($variant === null) {
        skip($release, "InterWorx {$release} has no variant for {$file}; nothing changed");
    }
    $plan[$file] = $variant;
}

// Stage every replacement next to its target before touching any target, so a failure here
// leaves the server exactly as it was.
$staged   = [];
$previous = [];
foreach ($plan as $file => $variant) {
    $target = "{$iworx}/{$file}";
    $backup = "{$pkg_dir}/" . basename($file) . '.orig';
    $stage  = "{$target}.intlic-new";

    $current = @file_get_contents($target);
    if ($current === false) {
        abortStaged($staged);
        fail($release, $plan, "Could not read {$target}; nothing changed", 42);
    }
    $previous[$file] = $current;

    if (!is_file($backup)) {
        if (@file_put_contents($backup, $current) === false) {
            abortStaged($staged);
            fail($release, $plan, "Could not back up {$target}; nothing changed", 42);
        }
        chmod($backup, 0600);
    }

    if (!@copy("{$pkg_dir}/src/{$variant}/{$file}", $stage)
        || !chown($stage, 'iworx') || !chgrp($stage, 'iworx') || !chmod($stage, 0600)) {
        $staged[] = $stage;
        abortStaged($staged);
        fail($release, $plan, "Could not stage the patched {$file}; nothing changed", 43);
    }
    $staged[] = $stage;
}

// Swap each staged file into place (rename is atomic within a directory). If one swap fails,
// put back every target already swapped.
$swapped = [];
foreach ($plan as $file => $variant) {
    $target = "{$iworx}/{$file}";
    if (!@rename("{$target}.intlic-new", $target)) {
        foreach ($swapped as $done) {
            $path = "{$iworx}/{$done}";
            @file_put_contents($path, $previous[$done]);
            @chown($path, 'iworx');
            @chgrp($path, 'iworx');
            @chmod($path, 0600);
        }
        abortStaged($staged);
        fail($release, $plan, "Could not move the patched {$file} into place; restored the originals", 44);
    }
    $swapped[] = $file;
}

report('installed', $release, $plan, 'Installed ' . describePlan($plan), 'info');
exit(0);

/**
 * The variant whose inclusive version range covers $version, or null.
 */
function pickVariant(array $variants, string $version): ?string
{
    foreach ($variants as $name => $range) {
        if (version_compare($version, $range['from'], '>=')
            && version_compare($version, $range['to'], '<=')) {
            return $name;
        }
    }
    return null;
}

function describePlan(array $plan): string
{
    $parts = [];
    foreach ($plan as $file => $variant) {
        $parts[] = "{$file} ({$variant})";
    }
    return implode(', ', $parts);
}

function abortStaged(array $staged): void
{
    foreach ($staged as $stage) {
        @unlink($stage);
    }
}

/**
 * Record the outcome in STATUS_FILE and syslog. Neither depends on the InterWorx license.
 */
function report(string $outcome, string $release, array $plan, string $message, string $priority): void
{
    $status = [
        'package' => 'interworx-internal-license',
        'outcome' => $outcome,
        'release' => $release,
        'files'   => $plan,
        'message' => $message,
        'time'    => gmdate('c'),
    ];
    $tmp = STATUS_FILE . '.tmp';
    if (@file_put_contents($tmp, json_encode($status, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n") !== false) {
        @chmod($tmp, 0644);
        @rename($tmp, STATUS_FILE);
    }

    exec('logger -t ' . LOG_TAG . ' -p ' . escapeshellarg("user.{$priority}") . ' '
        . escapeshellarg("{$outcome}: {$message}") . ' >/dev/null 2>&1');

    fwrite(STDERR, LOG_TAG . ": {$outcome}: {$message}\n");
}

/**
 * Unsupported build: record it and exit 0, so the RPM transaction succeeds and rollout tooling can
 * find these hosts by their status file.
 */
function skip(string $release, string $message): void
{
    report('skipped', $release, [], $message, 'warning');
    exit(0);
}

function fail(string $release, array $plan, string $message, int $code): void
{
    report('failed', $release, $plan, $message, 'err');
    exit($code);
}
