#!/usr/bin/env bash
# sync-envs-to-secrets.sh
# Copies all .env files from compose stack folders into the git-crypt secrets repo.
# Run as root on PD. Safe to re-run — overwrites stale copies.
set -euo pipefail

COMPOSE_ROOT="/mnt/docker-ssd/docker/compose"
SECRETS_REPO="/mnt/docker-ssd/docker/secrets"
ENV_DIR="${SECRETS_REPO}/env"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[+]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
die()  { echo -e "${RED}[✗]${NC} $*" >&2; exit 1; }

[[ -d "$SECRETS_REPO/.git" ]] || die "Secrets repo not found at ${SECRETS_REPO}. Run setup-secrets-repo.sh first."
[[ -d "$COMPOSE_ROOT" ]]     || die "Compose root not found at ${COMPOSE_ROOT}."

# Ensure git-crypt is unlocked — encrypted files show as binary if not
if file "${ENV_DIR}"/*.env &>/dev/null 2>&1 && file "${ENV_DIR}"/*.env 2>/dev/null | grep -q "Git crypt"; then
  die "Secrets repo appears to be locked. Run: git-crypt unlock /root/.git-crypt-secrets.key"
fi

info "Scanning ${COMPOSE_ROOT} for .env files..."
copied=0
skipped=0

while IFS= read -r -d '' envfile; do
  # Derive stack name: use "parent-child" for nested dirs (e.g. media/kima-hub → media-kima-hub)
  relpath="${envfile#${COMPOSE_ROOT}/}"   # e.g. media/kima-hub/.env
  stackpath="${relpath%/.env}"            # e.g. media/kima-hub
  stack="${stackpath//\//-}"              # e.g. media-kima-hub
  dest="${ENV_DIR}/${stack}.env"

  if [[ -f "$dest" ]]; then
    if ! diff -q "$envfile" "$dest" &>/dev/null; then
      cp "$envfile" "$dest"
      info "Updated:  ${stack}.env"
      copied=$((copied + 1))
    else
      warn "Unchanged: ${stack}.env — skipping"
      skipped=$((skipped + 1))
    fi
  else
    cp "$envfile" "$dest"
    info "Added:    ${stack}.env"
    copied=$((copied + 1))
  fi
done < <(find "$COMPOSE_ROOT" -maxdepth 3 -name ".env" -not -path "*/.git/*" -print0 | sort -z)

if [[ $copied -eq 0 ]]; then
  warn "Nothing new to commit ($skipped unchanged)."
  exit 0
fi

info "Committing ${copied} file(s) to secrets repo..."
cd "$SECRETS_REPO"
git add env/
git -c user.name="Fizzlepoof" -c user.email="admin@paccoco.com" \
  commit -m "chore: sync .env files from compose stacks

$(find "${ENV_DIR}" -name "*.env" -newer "${SECRETS_REPO}/.git/COMMIT_EDITMSG" 2>/dev/null \
  | sort | xargs -I{} basename {} | sed 's/^/  - /' || echo "  (see diff)")"

git push

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}  Done! ${copied} env file(s) synced, ${skipped} unchanged.${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "  Files in secrets repo:"
ls "${ENV_DIR}"/*.env 2>/dev/null | while read -r f; do echo "    $(basename "$f")"; done
echo ""
