<?php

declare(strict_types=1);

/*
 * eduVPN - End-user friendly VPN.
 *
 * Copyright: 2014-2023, The Commons Conservancy eduVPN Programme
 * SPDX-License-Identifier: AGPL-3.0+
 */

namespace Vpn\Portal\Cfg;

class RadiusAuthConfig
{
    use ConfigTrait;

    private array $configData;

    public function __construct(array $configData)
    {
        $this->configData = $configData;
    }

    /**
     * @return array<array{radiusHost:string,radiusPort:int,radiusSecret:string}>
     */
    public function serverList(): array
    {
        // this is horrible code!
        $serverInfoList = [];
        $serverList = $this->requireStringArray('serverList');
        foreach ($serverList as $serverInfo) {
            // split this thing in a good way to handle IPv6 addresses
            $serverInfo = trim($serverInfo);
            if (0 === strpos($serverInfo, '[')) {
                // IPv6
                // find first closing bracket
                if (false === $brPos = strpos($serverInfo, ']')) {
                    continue;
                }
                $ipSix = substr($serverInfo, 1, $brPos - 1);
                if (false === filter_var($ipSix, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                    // not valid IPv6 address
                    continue;
                }
                $e = explode(':', substr($serverInfo, $brPos + 2), 2);
                if (2 !== count($e)) {
                    continue;
                }
                $serverInfoList[] = ['radiusHost' => '[' . $ipSix . ']', 'radiusPort' => (int) $e[0], 'radiusSecret' => $e[1]];

                continue;
            }

            $e = explode(':', $serverInfo, 3);
            if (3 !== count($e)) {
                // malformed entry
                continue;
            }
            $serverInfoList[] = ['radiusHost' => $e[0], 'radiusPort' => (int) $e[1], 'radiusSecret' => $e[2]];
        }

        return $serverInfoList;
    }

    public function radiusRealm(): ?string
    {
        return $this->optionalString('radiusRealm');
    }

    public function nasIdentifier(): ?string
    {
        return $this->optionalString('nasIdentifier');
    }

    public function permissionAttribute(): ?int
    {
        return $this->optionalInt('permissionAttribute');
    }
}
