#!/bin/bash

# autoSMART Production Deployment Script
# Version: 1.0
# Description: Deploy autoSMART system to Proxmox cluster

set -e

# Configuration
DB_HOST="192.168.2.102"
DB_USER="autosmart"
DB_PASS="autoSMART2025!"
DB_NAME="autosmart"

CLUSTER_JSON="$(dirname "$0")/../cluster.json"
NODES=()
NODE_IPS=()
if [[ -f "$CLUSTER_JSON" ]] && command -v jq &> /dev/null; then
  while IFS= read -r node; do
    NODES+=("$(echo "$node" | jq -r '.hostname')")
    NODE_IPS+=("$(echo "$node" | jq -r '.ip')")
  done < <(jq -c '.cluster.nodes[]' "$CLUSTER_JSON")
fi
DEPLOY_DIR="/opt/autoSMART"
CONFIG_DIR="/etc/pve/autoSMART"

echo "🚀 autoSMART Production Deployment"
echo "=================================="

for idx in "${!NODES[@]}"; do
  NODE="${NODES[$idx]}"
  NODE_IP="${NODE_IPS[$idx]}"
  echo ""
  echo "🔧 Deploying to node: $NODE ($NODE_IP)"
  echo "------------------------"
    
  # Create directories
  ssh root@$NODE_IP "mkdir -p $DEPLOY_DIR $CONFIG_DIR"
    
  # Copy files
  scp -r /tmp/autoSMART-deploy/* root@$NODE_IP:$DEPLOY_DIR/
    
  # Install Perl dependencies
  ssh root@$NODE_IP "
    apt-get update -qq
    apt-get install -y libdbi-perl libdbd-pg-perl libjson-perl libfile-slurp-perl smartmontools
  "
    
  # Make scripts executable
  ssh root@$NODE_IP "chmod +x $DEPLOY_DIR/scripts/*.sh $DEPLOY_DIR/scripts/*.pl"
    
  # Create node-specific configuration
  ssh root@$NODE_IP "cat > $CONFIG_DIR/cluster-$NODE.conf << EOF
# autoSMART Configuration for $NODE
ExecStart=$DEPLOY_DIR/scripts/smart-collector-daemon.pl --config $CONFIG_DIR/cluster-$NODE.conf
Restart=always
RestartSec=30
User=root

[Install]
WantedBy=multi-user.target
EOF"
    
    # Enable service (but don't start yet)
    ssh root@192.168.2.$NODE "systemctl daemon-reload && systemctl enable autosmart"
    
    echo "✅ Node $NODE deployment complete"
done

# Test database connectivity
    
  # Install systemd service
  ssh root@$NODE_IP "cat > /etc/systemd/system/autosmart.service << EOF
echo ""
echo "🔍 Testing database connectivity..."
PGPASSWORD="$DB_PASS" psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c "
SELECT 
    COUNT(*) as total_drives,
    COUNT(DISTINCT current_node_id) as active_nodes
FROM hdd_inventory;
"

echo ""
echo "🎉 Production deployment complete!"
echo ""
echo "To start services on all nodes:"
echo "  for node in ebony ivory obsidian; do ssh root@192.168.2.\$node 'systemctl start autosmart'; done"
echo ""
echo "To monitor services:"
echo "  for node in ebony ivory obsidian; do echo \"=== \$node ===\"; ssh root@192.168.2.\$node 'systemctl status autosmart'; done"
echo ""
echo "Database monitoring:"
echo "  PGPASSWORD='$DB_PASS' psql -h $DB_HOST -U $DB_USER -d $DB_NAME -c 'SELECT * FROM storage_efficiency_stats;'"

# Cleanup
rm -rf /tmp/autoSMART-deploy

echo "✅ Deployment script complete!"
