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

REPO_ROOT="/home/westfarn/Documents/django_live_sites/Company_Site"
ENV_FILE="$REPO_ROOT/.env"
COMPOSE_FILE="$REPO_ROOT/docker-compose.prod.yml"
VALIDATE_SCRIPT="$REPO_ROOT/scripts/validate-env.sh"

if [[ $# -lt 1 || -z "${1:-}" ]]; then
  echo "Usage: $0 <checkout-directory>" >&2
  exit 1
fi

CHECKOUT="$1"
DEPLOY_MODE="${DEPLOY_MODE:-docker}"

if [[ "$DEPLOY_MODE" == "docker" ]]; then
  echo "Syncing application files to $REPO_ROOT (preserving server .env)..."
  rsync -a --delete \
    --exclude .git/ \
    --exclude .venv/ \
    --exclude .env \
    --exclude db.sqlite3 \
    --exclude staticfiles/ \
    "$CHECKOUT/" "$REPO_ROOT/"

  if [[ ! -f "$ENV_FILE" ]]; then
    echo "Missing $ENV_FILE on the server." >&2
    echo "Create it from .env.prod.example and configure production values." >&2
    exit 1
  fi

  bash "$VALIDATE_SCRIPT" "$ENV_FILE"

  cd "$REPO_ROOT"

  echo "Building Docker images..."
  docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" build

  echo "Starting containers..."
  docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" up -d --remove-orphans

  echo "Running database migrations..."
  docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" exec -T web \
    uv run python manage.py migrate --noinput

  echo "Deploy complete."
  docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" ps
  exit 0
fi

# Legacy venv/systemd deploy (DEPLOY_MODE=legacy)
APP_DIR="$REPO_ROOT/company_site"
VENV="$REPO_ROOT/.venv"
SETTINGS_DIR="$APP_DIR/company_site/settings"
LOCAL_SETTINGS="$APP_DIR/company_site/local_settings.py"

cp -r "$SETTINGS_DIR" /tmp/company_site_settings.bak
cp "$LOCAL_SETTINGS" /tmp/company_site_local_settings.py.bak 2>/dev/null || true

rsync -a --delete \
  --exclude .venv/ \
  --exclude .git/ \
  --exclude .env \
  --exclude 'company_site/company_site/settings/' \
  --exclude 'company_site/company_site/local_settings.py' \
  "$CHECKOUT/" "$REPO_ROOT/"

rm -rf "$SETTINGS_DIR"
cp -r /tmp/company_site_settings.bak "$SETTINGS_DIR"
cp /tmp/company_site_local_settings.py.bak "$LOCAL_SETTINGS" 2>/dev/null || true

uv sync --frozen --directory "$REPO_ROOT"
cd "$APP_DIR"
uv run python manage.py migrate --noinput
uv run python manage.py collectstatic --noinput

sudo systemctl restart company
