<?php

if (php_sapi_name() !== 'cli') {
    exit("This script must be run from the command line.\n");
}

if ($argc < 2) {
    exit("Usage: php ssl-check.php <domain>\nExample: php ssl-check.php mobile.eke-ree.com\n");
}

$inputDomain = trim($argv[1]);

function normalizeDomain(string $domain): string
{
    $domain = strtolower(trim($domain));
    $domain = preg_replace('#^https?://#', '', $domain);
    $domain = preg_replace('#/.*$#', '', $domain);
    $domain = preg_replace('/:\d+$/', '', $domain);
    return $domain;
}

function getBasicRootDomain(string $domain): string
{
    $parts = explode('.', $domain);
    $count = count($parts);

    if ($count <= 2) {
        return $domain;
    }

    return $parts[$count - 2] . '.' . $parts[$count - 1];
}

function checkSsl(string $domain): array
{
    $url = "https://{$domain}/";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_HEADER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_USERAGENT => 'PHP SSL Checker CLI',
    ]);

    curl_exec($ch);

    $errorNo = curl_errno($ch);
    $error = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $effectiveUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    curl_close($ch);

    return [
        'ok' => $errorNo === 0,
        'domain' => $domain,
        'error_no' => $errorNo,
        'error' => $error,
        'http_code' => $httpCode,
        'effective_url' => $effectiveUrl,
    ];
}

function printResult(array $result, string $label): void
{
    echo "\n{$label}\n";
    echo str_repeat('-', strlen($label)) . "\n";
    echo "Domain      : {$result['domain']}\n";
    echo "SSL status  : " . ($result['ok'] ? 'YES' : 'NO') . "\n";
    echo "HTTP code   : " . ($result['http_code'] ?: 'N/A') . "\n";
    echo "Final URL   : " . ($result['effective_url'] ?: 'N/A') . "\n";

    if (!$result['ok']) {
        echo "cURL error  : {$result['error']}\n";
    }
}

$normalized = normalizeDomain($inputDomain);

if (!filter_var($normalized, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
    exit("Invalid domain: {$inputDomain}\n");
}

$rootDomain = getBasicRootDomain($normalized);

echo "Input domain : {$inputDomain}\n";
echo "Normalized   : {$normalized}\n";
echo "Root domain  : {$rootDomain}\n";

$inputResult = checkSsl($normalized);
$rootResult = checkSsl($rootDomain);

printResult($inputResult, 'Input Domain Check');
printResult($rootResult, 'Root Domain Check');