#!/bin/bash

# autoSMART Schema v2 — Deploy to Tapia (secondary node)
# Date: 2026-05-20
# Copies updated collectors and restarts service

set -e

TAPIA_IP="192.168.2.93"
TAPIA_USER="root"
TARGET_DIR="/opt/autoSMART"
PROJECT_DIR="$(dirname "$(dirname "$0")")"

echo "🚀 Deploying autoSMART collectors to tapia ($TAPIA_IP)..."
echo ""

# 1. Copy updated scripts
echo "📦 Copying updated scripts..."
scp -q "$PROJECT_DIR/scripts/smart-collector-daemon.pl" "$TAPIA_USER@$TAPIA_IP:$TARGET_DIR/scripts/"
scp -q "$PROJECT_DIR/lib/SmartCollector.pm" "$TAPIA_USER@$TAPIA_IP:$TARGET_DIR/lib/"
echo "✅ Scripts copied"
echo ""

# 2. Stop service on tapia
echo "🛑 Stopping autosmart service on tapia..."
ssh "$TAPIA_USER@$TAPIA_IP" "systemctl stop autosmart" || true
sleep 2
echo "✅ Service stopped"
echo ""

# 3. Restart service
echo "🚀 Starting autosmart service on tapia..."
ssh "$TAPIA_USER@$TAPIA_IP" "systemctl start autosmart"
sleep 3
echo "✅ Service started"
echo ""

# 4. Verify service is running
echo "🔍 Verifying service status..."
if ssh "$TAPIA_USER@$TAPIA_IP" "systemctl is-active --quiet autosmart"; then
    echo "✅ autosmart service is running on tapia"
else
    echo "❌ autosmart service failed to start!"
    exit 1
fi
echo ""

# 5. Check recent logs
echo "📋 Last 5 log entries from tapia:"
ssh "$TAPIA_USER@$TAPIA_IP" "tail -5 /var/log/syslog | grep autosmart" || true
echo ""

echo "✅ Deploy to tapia complete!"
echo ""
echo "Next: Verify data collection:"
echo "  ssh root@ebony \"psql -h 192.168.2.102 -U postgres -d autosmart\""
echo "  SELECT node_id, COUNT(*) FROM smart_collection_events GROUP BY node_id;"
