#!/bin/sh

#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

# Setup EasyRSA pki
instance=$1
if [ -z $instance ]; then
    exit 1
fi

cn=$(uci get system.@system[0].hostname | cut -d '.' -f 1)
if [ -z "$cn" ]; then
    cn=NethSec
fi

# Set environment variables for EasyRSA
export EASYRSA_BATCH=1
export EASYRSA_CERT_EXPIRE=3650
export EASYRSA_CRL_DAYS=3650
export EASYRSA_REQ_CN=$cn

mkdir -p /etc/openvpn/$instance
if [ ! -f /etc/openvpn/$instance/pki/ca.crt ]; then
    cd /etc/openvpn/$instance
    (
        /usr/bin/easyrsa init-pki
        /usr/bin/easyrsa build-ca nopass
        openssl dhparam -dsaparam -out pki/dh.pem 2048
        /usr/bin/easyrsa build-server-full server nopass
        /usr/bin/easyrsa gen-crl
    ) &> /dev/null
fi