#!/usr/bin/env bash
set -euo pipefail

project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
env_file="$project_dir/.env.docker"

if [[ -e "$env_file" ]]; then
    echo ".env.docker existe deja; aucune modification effectuee."
    exit 0
fi

command -v openssl >/dev/null 2>&1 || {
    echo "openssl est requis pour generer les secrets." >&2
    exit 1
}

db_password="$(openssl rand -hex 24)"
root_password="$(openssl rand -hex 24)"
secret_key="$(openssl rand -hex 48)"
setup_token="$(openssl rand -hex 32)"
outlook_key="$(openssl rand -base64 32 | tr -d '\n')"

cat > "$env_file" <<EOF
OUTLOOK_ENCRYPTION_KEY=$outlook_key
SECRET_KEY=$secret_key
SETUP_TOKEN=$setup_token
DATABASE_URL=mysql+pymysql://gmao:$db_password@mariadb/gmao_db?charset=utf8mb4
UPLOAD_FOLDER=/app/app_new/uploads
MARIADB_ROOT_PASSWORD=$root_password
MARIADB_DATABASE=gmao_db
MARIADB_USER=gmao
MARIADB_PASSWORD=$db_password
DOCKER_GMAO_WORKDIR=/app
DOCKER_GMAO_ENVFILE=/app/.env.docker
EOF

chmod 600 "$env_file"
echo "Configuration creee dans .env.docker."
echo "Jeton du wizard: $setup_token"
echo "Conservez ce jeton dans un gestionnaire de mots de passe."
