#!/usr/bin/env bash
set -euo pipefail

BASE_URL="https://files.hashborn.space/miners/qub"
INSTALL_DIR="$HOME/miners/qub"
BIN_NAME="qli-Client"
SERVICE_NAME="qub-miner"

mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

echo "[1/5] Downloading miner..."
curl -fsSLo "$BIN_NAME" "$BASE_URL/$BIN_NAME"
chmod +x "$BIN_NAME"

echo "[2/5] Writing config..."
cat > appsettings.json <<EOF
{
  "ClientSettings": {
    "poolAddress": "wss://wps.qubic.li/ws",
    "alias": "$(hostname)",
    "trainer": {
      "cpu": true,
      "gpu": false,
      "gpuVersion": "CUDA",
      "cpuVersion": "",
      "cpuThreads": 0
    },
    "pps": true,
    "accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.[payload removed: 214 characters].LRmL57lFo0eEx2QIxW8n6CichJPu7DXRY-QPptfjOP5R0Bh4UoRy4OrXktilR4kqoOgEX64ozY-0sO8D6VVf7T6C_o64ydIcRda7pQJNA6AQdA2yFzQewesVjCGdvNSwuC0IODZZQYwP-iRrVfTB79yJ3IiHJwcHdlBkWKEXxoICmKuSSEgDv2bAj0bg3_ALK9OPyP-Lbwk9mPzxuQeKqRL5A19SyYhRvMzP1IzjeP3R1D0w04IYK9VPE8WyAhWQvYZGu02hmZczpdDUYjhJehaC8i7ZTlRZ3EMIWUTtUXlW9vCxv1zLj6hayrv_1h7CWDpdL9vlmOQrg629LbfWhQ",
    "qubicAddress": null,
    "idling": null
  }
}
EOF

echo "[3/5] Config ready:"
grep '"alias"\|"poolAddress"\|"cpu"\|"gpu"\|"pps"' appsettings.json || true

if command -v systemctl >/dev/null 2>&1; then
  echo "[4/5] Installing systemd service..."
  sudo tee /etc/systemd/system/${SERVICE_NAME}.service >/dev/null <<EOF
[Unit]
Description=Qubic Miner
After=network-online.target
Wants=network-online.target

[Service]
User=$USER
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/$BIN_NAME
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

  sudo systemctl daemon-reload
  sudo systemctl enable "${SERVICE_NAME}" >/dev/null 2>&1 || true
  sudo systemctl restart "${SERVICE_NAME}" || sudo systemctl start "${SERVICE_NAME}"
  echo "[5/5] Service status:"
  sudo systemctl --no-pager --full status "${SERVICE_NAME}" || true
else
  echo "[4/5] systemd not found, skipped service setup."
  echo "[5/5] Start manually:"
  echo "cd $INSTALL_DIR && ./$BIN_NAME"
fi
