#!/usr/bin/env bash
# generate-env.sh — create a local .mam.env from the committed .mam.env.example template.
#
# Behaviour:
#   - .mam.env absent            → copy .mam.env.example to .mam.env, print the path.
#   - .mam.env present           → no-op (leaves your edits intact), exit 0.
#   - .mam.env present --force    → overwrite .mam.env from .mam.env.example (backs up to .mam.env.bak).
#   - --migrate-legacy           → explicitly rename existing .env to .mam.env if absent.
#
# Paths are resolved relative to this script (repo root = parent of deploy/),
# so it works regardless of the caller's cwd.
#
# Usage: deploy/generate-env.sh [--force] [--migrate-legacy] [-h|--help]
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="$REPO_ROOT/.mam.env.example"
DST="$REPO_ROOT/.mam.env"
LEGACY_ENV="$REPO_ROOT/.env"

FORCE=0
MIGRATE=0
while [ $# -gt 0 ]; do
  case "$1" in
    --force) FORCE=1; shift ;;
    --migrate-legacy) MIGRATE=1; shift ;;
    -h|--help)
      echo "Usage: $0 [--force] [--migrate-legacy]"
      echo "  Create .mam.env from .mam.env.example."
      echo "  --force           overwrites an existing .mam.env (backs up to .mam.env.bak)."
      echo "  --migrate-legacy  explicitly renames an existing legacy .env to .mam.env."
      exit 0 ;;
    *) echo "ERROR: unknown arg: $1" >&2; echo "Usage: $0 [--force] [--migrate-legacy]" >&2; exit 2 ;;
  esac
done

if [ "$MIGRATE" = "1" ]; then
  if [ -f "$DST" ]; then
    echo "ERROR: cannot migrate: $DST already exists." >&2
    exit 1
  fi
  if [ ! -f "$LEGACY_ENV" ]; then
    echo "ERROR: cannot migrate: legacy file $LEGACY_ENV not found." >&2
    exit 1
  fi
  mv -f "$LEGACY_ENV" "$DST"
  chmod 0600 "$DST" 2>/dev/null || true
  echo "migrated: $LEGACY_ENV -> $DST"
  exit 0
fi

[ -f "$SRC" ] || { echo "ERROR: template not found: $SRC" >&2; exit 1; }

if [ -f "$DST" ] && [ "$FORCE" != "1" ]; then
  echo "no-op: $DST already exists (use --force to overwrite)"
  exit 0
fi

if [ -f "$DST" ] && [ "$FORCE" = "1" ]; then
  cp -p "$DST" "$DST.bak"
  echo "backed up existing .mam.env -> $DST.bak"
fi

cp "$SRC" "$DST"
chmod 0600 "$DST" 2>/dev/null || true
echo "created: $DST"
echo "Next: edit $DST and fill in any secrets (look for 'replace_me')."
