#!/usr/bin/env bash
# Deploy token-aggregation service to a Proxmox VMID

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VMID="${1:-5000}"
PROXMOX_HOST="${2:-192.168.11.12}"
PROXMOX_USER="${PROXMOX_USER:-root}"
SERVICE_PORT="${SERVICE_PORT:-3001}"

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_ok() { echo -e "${GREEN}[OK]${NC} $1"; }

log_info "Deploying token-aggregation to VMID $VMID"

# Build
log_info "Building..."
(cd "$SCRIPT_DIR" && pnpm run build)
log_ok "Built"

# Package
log_info "Creating package..."
PACKAGE_ITEMS=(dist src package.json tsconfig.json)
for optional in .env.example .env; do
  [ -e "$SCRIPT_DIR/$optional" ] && PACKAGE_ITEMS+=("$optional")
done
(cd "$SCRIPT_DIR" && tar czf /tmp/token-agg.tar.gz --exclude=node_modules "${PACKAGE_ITEMS[@]}")

# Deploy
log_info "Deploying..."
scp /tmp/token-agg.tar.gz "$PROXMOX_USER@$PROXMOX_HOST:/tmp/"
ssh "$PROXMOX_USER@$PROXMOX_HOST" "
  pct push $VMID /tmp/token-agg.tar.gz /tmp/token-agg.tar.gz
  pct exec $VMID -- bash -c '
    if ! command -v node &>/dev/null; then
      curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs postgresql-client
    fi
    command -v pnpm &>/dev/null || npm install -g pnpm@10
    mkdir -p /opt/token-aggregation && cd /opt/token-aggregation
    tar xzf /tmp/token-agg.tar.gz
    pnpm install --prod
    if [ ! -f .env ] && [ -f .env.example ]; then
      cp .env.example .env
    fi
  '
"

# Create service
ssh "$PROXMOX_USER@$PROXMOX_HOST" "pct exec $VMID -- bash -c 'cat > /etc/systemd/system/token-aggregation.service <<EOF
[Unit]
Description=Token Aggregation Service
After=network.target postgresql.service

[Service]
Type=simple
User=root
WorkingDirectory=/opt/token-aggregation
Environment=\"NODE_ENV=production\"
ExecStart=/usr/bin/pnpm start
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload && systemctl enable token-aggregation
'"

log_ok "Deployed. Configure /opt/token-aggregation/.env then: systemctl start token-aggregation"
