#!/bin/bash

# Arguments
USERNAME=$1

PKI_DIR=/storage/.kodi/userdata/addon_data/service.openvpn.server/

if [ ! -f "$PKI_DIR/server.dns" ]; then
   echo "Start creating server keys with:"
   echo "openvpn-generate-server"
   exit 1
fi

SERVER_DNS=$(cat "$PKI_DIR"/server.dns)

if [ -z "$USERNAME" ]; then
    echo "Usage: $0 <username>"
    exit 1
fi

echo "Generating user: $USERNAME"
echo "with server    : $SERVER_DNS"
echo "into directory : $PKI_DIR"
echo "Input PASSWORD to start."
read PASSWORD

if [ -z "$PASSWORD" ]; then
    echo "Password must NOT be empty !"
    exit 1
fi

# Paths
CA_CRT="$PKI_DIR/ca.crt"
CA_KEY="$PKI_DIR/ca.key"
TA_KEY="$PKI_DIR/ta.key"
OUTPUT_DIR="$PKI_DIR/clients"
USER_DIR="$OUTPUT_DIR/$USERNAME"

mkdir -p "$USER_DIR"
cd "$USER_DIR"

# 1. Create temporary openssl config
cat <<EOF > openssl_client.cnf
[ req ]
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
[ v3_client ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature
extendedKeyUsage = clientAuth
EOF

export OPENSSL_CONF="./openssl_client.cnf"

echo "--- Generating Client Config for: $USERNAME ---"

# 2. Generate Client Key with Password and CSR
# Usamos AES-256 para encriptar a chave privada
echo "[1/4] Creating Password Protected Client Key..."
openssl genrsa -aes256 -passout "pass:$PASSWORD" -out "$USERNAME.key" 2048

echo "[2/4] Creating Certificate Request (CSR)..."
openssl req -new -key "$USERNAME.key" -passin "pass:$PASSWORD" \
    -subj "/CN=$USERNAME" -out "$USERNAME.csr"

# 3. Sign Client Certificate
echo "[3/4] Signing Client Certificate..."
openssl x509 -req -in "$USERNAME.csr" -CA "$CA_CRT" -CAkey "$CA_KEY" -CAcreateserial \
    -out "$USERNAME.crt" -days 3650 -sha256 -extfile openssl_client.cnf -extensions v3_client

# 4. Create the Unified .ovpn file
echo "[4/4] Assembling unified .ovpn file..."
OUTPUT_FILE="$OUTPUT_DIR/$USERNAME.ovpn"

{
echo "client"
echo "dev tun"
echo "proto udp"
echo "remote $SERVER_DNS 1194"
echo "resolv-retry infinite"
echo "nobind"
echo "persist-key"
echo "persist-tun"
echo "remote-cert-tls server"
echo "cipher AES-256-GCM"
echo "auth SHA256"
echo "verb 3"

echo "<ca>"
cat "$CA_CRT"
echo "</ca>"

echo "<cert>"
openssl x509 -in "$USERNAME.crt"
echo "</cert>"

echo "<key>"
cat "$USERNAME.key"
echo "</key>"

echo "<tls-auth>"
cat "$TA_KEY"
echo "</tls-auth>"
echo "key-direction 1"
} > "$OUTPUT_FILE"

# 5. Cleanup
rm "$USERNAME.csr" openssl_client.cnf "$PKI_DIR/ca.srl" 2>/dev/null

echo "------------------------------------------------"
echo "Done! Client config created at: $OUTPUT_FILE"
echo "Note: The client will be prompted for the password during connection."

