#!/usr/bin/env bash
# Sincronizza il monorepo sul server di produzione (pre-Gitea)
set -euo pipefail

SERVER="${DEPLOY_SERVER:-eminux@192.168.1.146}"
DEST="${DEPLOY_PATH:-/opt/matchlivetv}"
SRC="$(cd "$(dirname "$0")/../.." && pwd)"

echo "Sync $SRC -> $SERVER:$DEST"

if ssh "$SERVER" 'command -v rsync >/dev/null 2>&1'; then
  rsync -avz --delete \
  --exclude '.git' \
  --exclude 'mobile/build' \
  --exclude 'mobile/.dart_tool' \
  --exclude 'backend/log' \
  --exclude 'backend/tmp' \
  --exclude 'backend/.bundle' \
  --exclude 'infra/.env' \
  --exclude 'node_modules' \
  "$SRC/" "$SERVER:$DEST/"
else
  echo "rsync non disponibile sul server, uso tar+scp..."
  tar -C "$SRC" -czf /tmp/matchlivetv-deploy.tar.gz \
    --exclude='./mobile/build' --exclude='./mobile/.dart_tool' \
    --exclude='./backend/log' --exclude='./backend/tmp' --exclude='./infra/.env' --exclude='./.git' .
  scp /tmp/matchlivetv-deploy.tar.gz "$SERVER:~/matchlivetv-deploy.tar.gz"
  ssh "$SERVER" "mkdir -p $DEST && tar -xzf ~/matchlivetv-deploy.tar.gz -C $DEST"
fi

echo "Done. On server run:"
echo "  cd $DEST/infra && cp .env.production.example .env  # edit secrets"
echo "  docker compose -f docker-compose.prod.yml up -d --build"
