#!/usr/bin/env bash
# generate-env.sh — create a local .env from the committed .env.example template.
#
# Behaviour:
#   - .env absent          → copy .env.example to .env, print the path.
#   - .env present         → no-op (leaves your edits intact), exit 0.
#   - .env present --force  → overwrite .env from .env.example (backs up to .env.bak).
#
# 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] [-h|--help]
set -euo pipefail

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

FORCE=0
while [ $# -gt 0 ]; do
  case "$1" in
    --force) FORCE=1; shift ;;
    -h|--help)
      echo "Usage: $0 [--force]"
      echo "  Create .env from .env.example. --force overwrites an existing .env."
      exit 0 ;;
    *) echo "ERROR: unknown arg: $1" >&2; echo "Usage: $0 [--force]" >&2; exit 2 ;;
  esac
done

[ -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 .env -> $DST.bak"
fi

cp "$SRC" "$DST"
echo "created: $DST"
echo "Next: edit $DST and fill in any secrets (look for 'replace_me')."
