#!/usr/bin/env bash
# Build the static site locally, then replace the server directory with it.
#
#   - Builds on THIS machine (npm run build -> ./out).
#   - Streams out/ over a single SSH connection (tar pipe) and swaps the
#     contents of the target dir on the server. No rsync/sshpass required.
#
# Password handling:
#   - If `sshpass` is installed AND DEPLOY_PASSWORD is set (env or .env.deploy),
#     the deploy is fully unattended.
#   - Otherwise SSH prompts for the password once (interactive).
#
# Config (override via env or .env.deploy):
set -euo pipefail
cd "$(git rev-parse --show-toplevel 2>/dev/null || dirname "$(dirname "$0")")"

# Optional local secrets file (gitignored).
[ -f .env.deploy ] && . ./.env.deploy

DEPLOY_HOST="${DEPLOY_HOST:-185.226.116.88}"
DEPLOY_USER="${DEPLOY_USER:-ubuntu}"
DEPLOY_PATH="${DEPLOY_PATH:-/var/www/aramland-front}"
DEPLOY_PASSWORD="${DEPLOY_PASSWORD:-}"

echo "▸ Building locally (clean)…"
# Remove caches so the production build never type-checks a stale `.next/dev`
# validator (tsconfig includes .next/dev/types) and never ships stale out/ files.
rm -rf .next out
npm run build

if [ ! -d out ]; then
  echo "✗ Build did not produce ./out" >&2
  exit 1
fi

# Pick the SSH command: unattended with sshpass, else interactive prompt.
ssh_cmd=(ssh -o StrictHostKeyChecking=no "$DEPLOY_USER@$DEPLOY_HOST")
if command -v sshpass >/dev/null 2>&1 && [ -n "$DEPLOY_PASSWORD" ]; then
  ssh_cmd=(sshpass -p "$DEPLOY_PASSWORD" "${ssh_cmd[@]}")
else
  echo "ℹ sshpass/password not available — SSH will prompt for the password."
fi

echo "▸ Uploading to $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH …"
# Replace the directory contents (incl. dotfiles) then extract the new build.
tar -C out -czf - . | "${ssh_cmd[@]}" \
  "set -e; mkdir -p '$DEPLOY_PATH'; find '$DEPLOY_PATH' -mindepth 1 -delete; tar -C '$DEPLOY_PATH' -xzf -"

echo "✓ Deployed to $DEPLOY_HOST:$DEPLOY_PATH"
