#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
EMAIL_GEN_DIR="$ROOT_DIR/email-gen"

if [[ ! -d "$EMAIL_GEN_DIR/.git" ]]; then
  echo "[error] email-gen git repo not found: $EMAIL_GEN_DIR"
  exit 1
fi

BRANCH="${1:-}"

cd "$EMAIL_GEN_DIR"

echo "[info] fetching email-gen..."
git fetch --all --prune

if [[ -n "$BRANCH" ]]; then
  echo "[info] checking out branch: $BRANCH"
  git checkout "$BRANCH"
fi

CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
echo "[info] pulling branch: $CURRENT_BRANCH"
git pull --ff-only origin "$CURRENT_BRANCH"

echo "[info] rebuilding email-gen-api container..."
cd "$ROOT_DIR"
docker compose -f docker-compose.prod.yml up -d --build email-gen-api

echo "[ok] email-gen updated and email-gen-api restarted"
