#!/bin/bash
# agent.sh - Miner installation script for auto-registration
set -e

if [ -z "$1" ]; then
  echo "Uso: curl -fsSL https://hive.cilixs.com/agent.sh | bash -s -- <INSTALL_SECRET>"
  exit 1
fi

INSTALL_SECRET="$1"
SERVER_URL="https://hive.cilixs.com"

echo "=== HIVE MONERO TELEMETRY AGENT SETUP ==="

mkdir -p /opt/monero-monitor
cd /opt/monero-monitor

echo "[1/3] Descargando telemetry_agent.py..."
curl -fsSL "$SERVER_URL/telemetry_agent.py" -o telemetry_agent.py

echo "[2/3] Auto-registrando minero '$(hostname)' en el servidor..."
RESPONSE=$(curl -s -X POST "$SERVER_URL/api/workers" \
  -H "X-Install-Secret: $INSTALL_SECRET" \
  -H "Content-Type: application/json" \
  -d "{"name":"$(hostname)","type":"CPU"}")

if echo "$RESPONSE" | grep -q "error"; then
  echo "Error durante la auto-registración:"
  echo "$RESPONSE"
  exit 1
fi

# Extract token and id from JSON using python (since python is guaranteed on mining rigs)
WORKER_ID=$(python3 -c "import sys, json; print(json.loads(sys.argv[1]).get('id',''))" "$RESPONSE")
WORKER_TOKEN=$(python3 -c "import sys, json; print(json.loads(sys.argv[1]).get('token',''))" "$RESPONSE")

if [ -z "$WORKER_ID" ] || [ -z "$WORKER_TOKEN" ]; then
  echo "Error: No se pudo obtener la credencial de auto-registro."
  exit 1
fi

echo "¡Auto-registro exitoso!"
echo "Miner ID: $WORKER_ID"

echo "[3/3] Escribiendo config.json..."
cat << EOF > config.json
{
  "server_url": "$SERVER_URL",
  "worker_id": "$WORKER_ID",
  "worker_token": "$WORKER_TOKEN"
}
EOF

echo "Creando servicio systemd..."
cat << EOF > /etc/systemd/system/monero-telemetry.service
[Unit]
Description=Monero Telemetry Agent
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/monero-monitor
ExecStart=/usr/bin/python3 telemetry_agent.py
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable monero-telemetry
systemctl start monero-telemetry

echo "========================================="
echo "¡Monero Telemetry Agent configurado y corriendo!"
echo "========================================="
