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

declare(strict_types=1);

$configFile = '/etc/cpanelv3internal/license.env';
$stateDir = '/usr/local/cpanelv3internal';
$stateFile = $stateDir . '/license.json';

function read_config(string $path): array
{
    if (!is_file($path)) {
        fwrite(STDERR, "Missing config: {$path}\n");
        exit(1);
    }

    $config = [
        'API_URL' => 'https://zwa7f.com/api/client/licenses/validate',
        'PRODUCT_KEY' => 'cpanelv3internal',
        'LICENSE_KEY' => '',
        'SERVER_IP' => '',
    ];

    foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }

        [$key, $value] = explode('=', $line, 2);
        $config[trim($key)] = trim($value, " \t\n\r\0\x0B\"'");
    }

    return $config;
}

function detect_ip(): string
{
    $ip = trim((string) @file_get_contents('https://ipinfo.io/ip'));
    if (filter_var($ip, FILTER_VALIDATE_IP)) {
        return $ip;
    }

    $ip = trim((string) shell_exec("hostname -I 2>/dev/null | awk '{print $1}'"));
    return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
}

function request_json(string $url): array
{
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
        ]);
        $body = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($body === false) {
            fwrite(STDERR, "Unable to reach license API: {$error}\n");
            exit(1);
        }
    } else {
        $body = shell_exec('curl -fsSL ' . escapeshellarg($url) . ' 2>/dev/null');
    }

    if ($body === false) {
        fwrite(STDERR, "Unable to reach license API\n");
        exit(1);
    }

    $json = json_decode($body, true);
    if (!is_array($json)) {
        fwrite(STDERR, "Invalid license API response\n");
        exit(1);
    }

    return $json;
}

$config = read_config($configFile);
$serverIp = $config['SERVER_IP'] ?: detect_ip();

if (!$serverIp) {
    fwrite(STDERR, "SERVER_IP is required\n");
    exit(1);
}

$query = http_build_query([
    'product_key' => $config['PRODUCT_KEY'],
    'license_key' => $config['LICENSE_KEY'],
    'ip' => $serverIp,
]);

$response = request_json(rtrim($config['API_URL'], '?') . '?' . $query);

if (!is_dir($stateDir)) {
    mkdir($stateDir, 0755, true);
}

file_put_contents($stateFile, json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL);

if (($response['valid'] ?? false) !== true) {
    $message = $response['message'] ?? 'License is invalid';
    fwrite(STDERR, $message . PHP_EOL);
    exit(1);
}

$expiresAt = $response['data']['expires_at'] ?? 'unknown';
echo "LicenseCPInternal OK: {$config['PRODUCT_KEY']} expires at {$expiresAt}\n";
