#!/bin/sh
set -eu

if [ ! -f deploy/vps/.env ]; then
    echo "Missing deploy/vps/.env"
    exit 1
fi

JWT_PASSPHRASE=$(grep '^JWT_PASSPHRASE=' deploy/vps/.env | cut -d= -f2-)

if [ -z "$JWT_PASSPHRASE" ]; then
    echo "JWT_PASSPHRASE is empty in deploy/vps/.env"
    exit 1
fi

mkdir -p backend/config/jwt

openssl genrsa -aes256 -passout "pass:${JWT_PASSPHRASE}" -out backend/config/jwt/private.pem 4096
openssl rsa -pubout -passin "pass:${JWT_PASSPHRASE}" -in backend/config/jwt/private.pem -out backend/config/jwt/public.pem

chmod 600 backend/config/jwt/private.pem
chmod 644 backend/config/jwt/public.pem

echo "JWT keypair generated in backend/config/jwt"
