#!/usr/bin/env bash
# First-time setup: creates .env with fresh secrets and your login.
# Needs: docker, openssl. Safe to re-run (it asks before overwriting).
set -euo pipefail
cd "$(dirname "$0")"

AUTHELIA_IMAGE="authelia/authelia:4.39"

if [ -f .env ]; then
  read -r -p ".env already exists. Overwrite it and make new secrets? [y/N] " answer
  [ "${answer:-N}" = "y" ] || { echo "Left .env as it was."; exit 0; }
fi

read -r -p "Your domain (for example example.com): " DOMAIN
read -r -p "Login username [admin]: " USERNAME
USERNAME="${USERNAME:-admin}"
read -r -p "Your email (stored only in authelia/users_database.yml): " EMAIL
read -r -s -p "Login password (12+ characters): " PASSWORD
echo
read -r -s -p "Type it again: " PASSWORD2
echo

if [ "$PASSWORD" != "$PASSWORD2" ]; then
  echo "The passwords didn't match. Run ./setup.sh again." >&2
  exit 1
fi
if [ "${#PASSWORD}" -lt 12 ]; then
  echo "Use at least 12 characters. Run ./setup.sh again." >&2
  exit 1
fi

echo "Hashing your password (this pulls the Authelia image the first time)..."
HASH="$(docker run --rm "$AUTHELIA_IMAGE" authelia crypto hash generate argon2 --password "$PASSWORD" | sed -n 's/^Digest: //p')"
if [ -z "$HASH" ]; then
  echo "Could not create the password hash. Check that Docker is running." >&2
  exit 1
fi

umask 077
cat > .env <<EOF
DOMAIN=${DOMAIN}
AUTHELIA_SESSION_SECRET=$(openssl rand -hex 32)
AUTHELIA_STORAGE_ENCRYPTION_KEY=$(openssl rand -hex 32)
AUTHELIA_JWT_SECRET=$(openssl rand -hex 32)
EOF

cat > authelia/users_database.yml <<EOF
---
users:
  ${USERNAME}:
    disabled: false
    displayname: '${USERNAME}'
    password: '${HASH}'
    email: '${EMAIL}'
    groups:
      - admins
EOF

echo
echo "Done. Next:"
echo "  1. Point DNS for ${DOMAIN} and *.${DOMAIN} at this server, and forward ports 80 and 443 to it."
echo "  2. Run: docker compose up -d"
echo "  3. Open https://auth.${DOMAIN} and sign in as ${USERNAME}."
