#!/usr/bin/env bash

set -euo pipefail

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

# Default deploy target (can be overridden by positional args)
DEFAULT_REMOTE="root@111.228.39.147"
DEFAULT_REMOTE_APP_DIR="/root/deerflow2"

usage() {
  cat <<'EOF'
Usage:
  ./scripts/deploy-frontend-standalone.sh [remote] [remote_app_dir]

Arguments:
  remote          SSH target, optional. Default: root@111.228.39.147
  remote_app_dir  Remote deerflow2 root dir, optional. Default: /root/deerflow2

Example:
  ./scripts/deploy-frontend-standalone.sh
  ./scripts/deploy-frontend-standalone.sh ubuntu@1.2.3.4 /opt/deerflow2

Notes:
  - Run this script on your local machine (build machine), not on the server.
  - Requires: pnpm, rsync, ssh
  - Script will run:
      sudo systemctl daemon-reload
      sudo systemctl restart deerflow.service
EOF
}

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

if [ "$#" -gt 2 ]; then
  usage
  exit 1
fi

REMOTE="${1:-$DEFAULT_REMOTE}"
REMOTE_APP_DIR="${2:-$DEFAULT_REMOTE_APP_DIR}"

echo "==> Deploy target:"
echo "    remote: $REMOTE"
echo "    app dir: $REMOTE_APP_DIR"

echo "==> Building frontend (standalone)..."
pnpm -C frontend build

echo "==> Uploading standalone server..."
rsync -azP --delete --info=progress2 \
  frontend/.next/standalone/ \
  "$REMOTE:$REMOTE_APP_DIR/frontend/.next/standalone/"

echo "==> Uploading static assets..."
rsync -azP --info=progress2 \
  frontend/.next/static/ \
  "$REMOTE:$REMOTE_APP_DIR/frontend/.next/standalone/.next/static/"

echo "==> Uploading public assets..."
rsync -azP --info=progress2 \
  frontend/public/ \
  "$REMOTE:$REMOTE_APP_DIR/frontend/.next/standalone/public/"

echo "==> Reloading systemd and restarting deerflow.service on remote host..."
ssh "$REMOTE" "sudo systemctl daemon-reload && sudo systemctl restart deerflow.service"

echo "==> Done."
