#!/bin/sh
set -eu

APP_ENV="${APP_ENV:-prod}"
APP_DEBUG="${APP_DEBUG:-0}"
JWT_SECRET_KEY_PATH="${JWT_SECRET_KEY:-/var/www/html/config/jwt/private.pem}"
JWT_PUBLIC_KEY_PATH="${JWT_PUBLIC_KEY:-/var/www/html/config/jwt/public.pem}"
JWT_SECRET_KEY_DIR="$(dirname "$JWT_SECRET_KEY_PATH")"
JWT_PUBLIC_KEY_DIR="$(dirname "$JWT_PUBLIC_KEY_PATH")"

if [ "$APP_ENV" = "prod" ] && [ "$APP_DEBUG" != "0" ]; then
    echo "Refusing to start with APP_DEBUG enabled in production."
    exit 1
fi

if [ -z "${APP_SECRET:-}" ]; then
    echo "APP_SECRET is required."
    exit 1
fi

if [ -z "${JWT_PASSPHRASE:-}" ]; then
    echo "JWT_PASSPHRASE is required."
    exit 1
fi

mkdir -p var/cache var/log var/sessions "$JWT_SECRET_KEY_DIR" "$JWT_PUBLIC_KEY_DIR"
chown -R www-data:www-data "$JWT_SECRET_KEY_DIR" "$JWT_PUBLIC_KEY_DIR"

export JWT_SECRET_KEY="$JWT_SECRET_KEY_PATH"
export JWT_PUBLIC_KEY="$JWT_PUBLIC_KEY_PATH"

if [ ! -f "$JWT_SECRET_KEY_PATH" ] || [ ! -f "$JWT_PUBLIC_KEY_PATH" ]; then
    echo "JWT keypair missing, generating with lexik:jwt:generate-keypair..."
    su -s /bin/sh www-data -c 'php bin/console lexik:jwt:generate-keypair --overwrite --no-interaction'
fi

if [ ! -f "$JWT_SECRET_KEY_PATH" ] || [ ! -f "$JWT_PUBLIC_KEY_PATH" ]; then
    echo "Failed to generate JWT keypair at: $JWT_SECRET_KEY_PATH and $JWT_PUBLIC_KEY_PATH"
    exit 1
fi

chown www-data:www-data "$JWT_SECRET_KEY_PATH" "$JWT_PUBLIC_KEY_PATH"
chmod 644 "$JWT_SECRET_KEY_PATH" "$JWT_PUBLIC_KEY_PATH"

chown -R www-data:www-data var

exec "$@"
