#!/usr/bin/env bash
# Hands-On tutorial — generate a self-signed cert for *.localtest.me.
# Drops the cert + key into ./nginx/certs/ and trusts the cert in the
# user's macOS login keychain.
#
# Run once per workstation. Linux users: ignore the keychain step and
# import the cert into your browser manually.

set -euo pipefail

CERT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/nginx/certs"
mkdir -p "${CERT_DIR}"

# 1. Self-signed cert covering every localtest.me subdomain we use.
openssl req -x509 -newkey rsa:2048 -nodes -keyout "${CERT_DIR}/localtest.me.key" \
  -out "${CERT_DIR}/localtest.me.crt" -days 825 \
  -subj "/CN=frontend.localtest.me" \
  -addext "subjectAltName=DNS:frontend.localtest.me,DNS:auth.localtest.me,DNS:api.localtest.me,DNS:backend.localtest.me"

echo "✓ Certs written to ${CERT_DIR}"

# 2. Trust the cert (macOS only — silently skipped elsewhere).
if [[ "$(uname)" == "Darwin" ]]; then
  security add-trusted-cert -d -k ~/Library/Keychains/login.keychain-db \
    -r trustRoot "${CERT_DIR}/localtest.me.crt" 2>/dev/null \
    && echo "✓ Cert added to macOS login keychain as a trusted root." \
    || echo "⚠ Could not auto-trust the cert; trust it manually in Keychain Access."
fi
