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

if [[ $EUID -eq 0 ]]; then
  echo "Run this script as the application user (not root)." >&2
  exit 1
fi

APP_DIR="${APP_DIR:-/srv/myroadtrip}"
REPO_URL="${REPO_URL:-https://github.com/HectorLayak/RoadTripper.git}"
BRANCH="${BRANCH:-main}"
ENV_FILE="${ENV_FILE:-$APP_DIR/.env.production}"
BUILD_WEB="${BUILD_WEB:-false}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing environment file at $ENV_FILE" >&2
  echo "Copy your production secrets before deploying." >&2
  exit 1
fi

mkdir -p "$APP_DIR"
cd "$APP_DIR"

if [[ ! -d repo ]]; then
  git clone "$REPO_URL" repo
fi

cd repo
git fetch origin
git checkout "$BRANCH"
git pull --ff-only origin "$BRANCH"

export NODE_ENV=production
corepack enable pnpm >/dev/null 2>&1 || true
pnpm install --frozen-lockfile

pnpm --filter @my-roadtrip/api build

if [[ "$BUILD_WEB" == "true" ]]; then
  pnpm --filter @my-roadtrip/web build
fi

echo "Deployment assets ready. Ensure systemd services are restarted:"
echo "  sudo systemctl restart myroadtrip-api"
echo "  sudo systemctl restart myroadtrip-web (if applicable)"
