<?php

declare(strict_types=1);

/*
 * Copyright (c) 2023-2024 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

require_once __DIR__ . '/autoload.php';

use fkooman\Radius\ClientConfig;
use fkooman\Radius\Exception\AccessChallengeException;
use fkooman\Radius\Exception\AccessRejectException;
use fkooman\Radius\LoggerInterface;
use fkooman\Radius\RadiusClient;
use fkooman\Radius\RadiusPacket;
use fkooman\Radius\ServerInfo;

class ErrorLogger implements LoggerInterface
{
    public function error(string $logMessage): void
    {
        error_log(sprintf('[%s] %s', __METHOD__, $logMessage));
    }

    public function warning(string $logMessage): void
    {
        error_log(sprintf('[%s] %s', __METHOD__, $logMessage));
    }

    public function info(string $logMessage): void
    {
        error_log(sprintf('[%s] %s', __METHOD__, $logMessage));
    }

    public function debug(string $logMessage): void
    {
        error_log(sprintf('[%s] %s', __METHOD__, $logMessage));
    }
}

function myGetEnv(string $envVar, string $defaultValue): string
{
    $envVal = getenv($envVar);
    if (!is_string($envVal)) {
        return $defaultValue;
    }

    return $envVal;
}

function accessRequest(RadiusClient $radiusClient, string $userName, string $userPassword, ?RadiusPacket $challengeResponse = null): RadiusPacket
{
    try {
        return $radiusClient->accessRequest($userName, $userPassword, $challengeResponse);
    } catch (AccessChallengeException $e) {
        $challengeResponse = $e->radiusPacket();
        echo $challengeResponse->attributeCollection() . PHP_EOL;
        echo 'Answer to Challenge: ';
        $userPassword = trim(fgets(STDIN));

        return accessRequest($radiusClient, $userName, $userPassword, $challengeResponse);
    }
}

if ($argc < 3) {
    echo 'SYNTAX: ' . $argv[0] . ' User-Name User-Password' . PHP_EOL;
    exit(1);
}

$radiusClient = new RadiusClient(
    new ClientConfig(myGetEnv('NAS_ID', 'My NAS'), (bool) myGetEnv('REQUIRE_MA', '1')),
    new ErrorLogger()
);

$radiusClient->addServer(
    new ServerInfo(
        myGetEnv('SERVER_URI', 'udp://127.0.0.1:1812'),
        myGetEnv('SHARED_SECRET', 's3cr3t'),
        (int) myGetEnv('SERVER_MAX_TRIES', '3'),
        (int) myGetEnv('SERVER_TIMEOUT', '3')
    )
);

try {
    $accessResponse = accessRequest($radiusClient, $argv[1], $argv[2]);
    echo '******* OK *******' . PHP_EOL;
    echo $accessResponse->attributeCollection() . PHP_EOL;
} catch (AccessRejectException $e) {
    $rejectResponse = $e->radiusPacket();
    echo '******* FAIL *******' . PHP_EOL;
    echo $rejectResponse->attributeCollection() . PHP_EOL;

    exit(1);
} catch (Exception $e) {
    echo 'ERROR: ' . $e->getMessage() . PHP_EOL;

    exit(1);
}
