<?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;

use PDO;

class DbConfig
{
    use ConfigTrait;

    private array $configData;

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

    public function baseDir(): string
    {
        return $this->requireString('baseDir');
    }

    public function schemaDir(): string
    {
        return '/var/www/vpn-user-portal/schema';
    }

    public function dbDsn(): string
    {
        return $this->requireString('dbDsn', 'sqlite://' . $this->baseDir() . '/data/db.sqlite');
    }

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

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

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

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

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

    public function dbOptions(): array
    {
        $dbOptions = [];
        if (0 === strpos($this->dbDsn(), 'mysql:')) {
            // MySQL / MariaDB
            if (null !== $tlsCa = $this->tlsCa()) {
                $dbOptions[PDO::MYSQL_ATTR_SSL_CA] = $tlsCa;
                // it seems this flag is enabled by default, but I don't think
                // it hurts to explicity set it here...
                $dbOptions[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = 1;
            }
            if (null !== $tlsCert = $this->tlsCert()) {
                $dbOptions[PDO::MYSQL_ATTR_SSL_CERT] = $tlsCert;
            }
            if (null !== $tlsKey = $this->tlsKey()) {
                $dbOptions[PDO::MYSQL_ATTR_SSL_KEY] = $tlsKey;
            }
        }

        return $dbOptions;
    }
}
