<?php
declare(strict_types=1);

/** Alpine BE WireGuard peer lifecycle (wg set) for remote-access sessions. */
final class WireGuardPeerProvisioner {
    private function __construct() {}

    public static function isEnabled(): bool {
        return (bool) cfg('remote_access.provision_peers', true);
    }

    public static function interfaceName(): string {
        return (string) cfg('remote_access.wg_interface', 'wg0');
    }

    public static function publicKeyFromPrivate(string $privateKey): string {
        $priv = trim($privateKey);
        if ($priv === '') {
            return '';
        }
        $pub = trim((string) @shell_exec('echo ' . escapeshellarg($priv) . ' | wg pubkey 2>/dev/null') ?: '');
        return $pub;
    }

    public static function addClientPeer(string $clientPublicKey, string $clientAddressCidr): bool {
        if (!self::isEnabled()) {
            return true;
        }
        $pub = trim($clientPublicKey);
        if ($pub === '' || str_starts_with($pub, 'dev-placeholder-pub-')) {
            return false;
        }
        $iface = self::interfaceName();
        $allowed = trim($clientAddressCidr);
        if ($allowed === '') {
            $allowed = WireGuardAddressPool::allocateClientAddress('default');
        }
        $code = self::runWg(
            'set ' . escapeshellarg($iface)
            . ' peer ' . escapeshellarg($pub)
            . ' allowed-ips ' . escapeshellarg($allowed)
        );
        return $code === 0;
    }

    public static function removeClientPeer(?string $clientPublicKey): void {
        if (!self::isEnabled()) {
            return;
        }
        $pub = trim((string) $clientPublicKey);
        if ($pub === '' || str_starts_with($pub, 'dev-placeholder-pub-')) {
            return;
        }
        $iface = self::interfaceName();
        self::runWg(
            'set ' . escapeshellarg($iface)
            . ' peer ' . escapeshellarg($pub)
            . ' remove'
        );
    }

    private static function runWg(string $args): int {
        $prefix = rtrim((string) cfg('remote_access.wg_set_prefix', ''), " \t");
        $cmd = ($prefix !== '' ? $prefix . ' ' : '') . 'wg ' . $args;
        exec($cmd . ' 2>&1', $out, $code);
        if ($code !== 0) {
            error_log('WireGuardPeerProvisioner: ' . $cmd . ' failed: ' . implode(' ', $out));
        }
        return $code;
    }
}
