#!/bin/bash
# install.sh - Central server installation script for LXC CT-102
set -e

echo "=== HIVE MONERO DASHBOARD SERVER INSTALLER ==="
if [ "$EUID" -ne 0 ]; then
  echo "Error: Correr como root o sudo."
  exit 1
fi

echo "[1/5] Actualizando paquetes..."
apt-get update && apt-get install -y curl git build-essential

# Check Node version
if ! command -v node &> /dev/null || [ $(node -v | cut -d'.' -f1 | tr -d 'v') -lt 20 ]; then
  echo "[2/5] Instalando Node.js v20..."
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
else
  echo "[2/5] Node.js $(node -v) ya está instalado."
fi

echo "[3/5] Clonando repositorio y configurando..."
if [ ! -d "/opt/hive-monero-monitor" ]; then
  git clone https://github.com/grindecomx/HIVE-MINER-DASHBOARD.git /opt/hive-monero-monitor
fi

cd /opt/hive-monero-monitor
npm install --production

# Generate random secret if not exists
if [ ! -f ".env" ]; then
  echo "[4/5] Creando archivo de configuración .env..."
  SECRET=$(head -c 16 /dev/urandom | sha256sum | cut -d' ' -f1)
  echo "INSTALL_SECRET=$SECRET" > .env
  echo "RECEIVER_EMAIL=x12102711@icloud.com" >> .env
  echo "Configuración inicial creada en .env."
  echo "!!! GUARDAR TU TOKEN DE INSTALACIÓN: $SECRET"
fi

echo "[5/5] Registrando servicio en Systemd..."
cat << 'EOF' > /etc/systemd/system/hive-dashboard.service
[Unit]
Description=Hive Monero Monitor Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/hive-monero-monitor
ExecStart=/usr/bin/npx tsx server.ts
Restart=always
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable hive-dashboard
systemctl start hive-dashboard

echo "================================================="
echo "¡Servidor Hive Monero Monitor instalado con éxito!"
echo "Servicio corriendo en puerto 3000."
echo "Clave de instalación para agentes (INSTALL_SECRET):"
cat .env | grep INSTALL_SECRET | cut -d'=' -f2
echo "================================================="
