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

# Deploy pi-worker to cr-server-new
SERVER="root@159.195.60.33"
CONTAINER="cr-server-new"
DEPLOY_PATH="/opt/pi-worker"

echo "🚀 Deploying Pi Worker to cr-server-new..."

# Sync files to server
echo "📦 Syncing files..."
rsync -avz --exclude=node_modules --exclude=logs --exclude=.env \
  ./ ${SERVER}:${DEPLOY_PATH}/

# Copy .env if it exists locally
if [ -f .env ]; then
  echo "🔐 Syncing .env..."
  rsync -avz .env ${SERVER}:${DEPLOY_PATH}/.env
fi

# Push into container and build
echo "🔨 Building inside cr-server-new..."
ssh ${SERVER} << 'EOF'
  incus file push -r /root/pi-worker cr-server-new/opt/
  incus exec cr-server-new -- bash -c "
    cd /opt/pi-worker
    bun install
    echo '✅ Dependencies installed'
  "
EOF

echo "🏃 Starting Pi Worker..."
ssh ${SERVER} << 'EOF'
  incus exec cr-server-new -- bash -c "
    cd /opt/pi-worker
    # Stop existing instance
    pkill -f 'bun.*pi-worker' || true
    # Start in background
    nohup bun run src/index.ts > /var/log/pi-worker.log 2>&1 &
    echo '✅ Pi Worker started (PID: $!)'
  "
EOF

echo "🎉 Deployment complete!"
echo "Health check: ssh ${SERVER} 'incus exec ${CONTAINER} -- curl -s http://localhost:8787/health'"
