#!/usr/bin/env bash
set -e

MINER_KEY="${1:-}"
BASE_URL="https://explorer.malairtebitcoin.com/downloads"
INSTALL_DIR="/usr/local/bin"
DATA_DIR="/var/lib/malairte-node"
SERVICE_FILE="/etc/systemd/system/malairte-node.service"

RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m'; NC='\033[0m'

echo ""
echo "  ███╗   ███╗██╗      ██████╗ ████████╗"
echo "  ████╗ ████║██║     ██╔══██╗╚══██╔══╝"
echo "  ██╔████╔██║██║     ██████╔╝   ██║   "
echo "  ██║╚██╔╝██║██║     ██╔══██╗   ██║   "
echo "  ██║ ╚═╝ ██║███████╗██║  ██║   ██║   "
echo "  ╚═╝     ╚═╝╚══════╝╚═╝  ╚═╝   ╚═╝   "
echo "  Malairte Blockchain Node — Linux Setup"
echo ""

if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}Error: Please run as root (sudo bash setup-linux.sh)${NC}"
  exit 1
fi

if [ -z "$MINER_KEY" ]; then
  echo -e "${RED}Error: Miner private key required.${NC}"
  echo "Usage: bash setup-linux.sh <YOUR_PRIVATE_KEY_HEX>"
  echo "Get your key from https://explorer.malairtebitcoin.com/onboarding"
  exit 1
fi

ARCH=$(uname -m)
case "$ARCH" in
  x86_64)  BINARY="malairte-node-linux-amd64"  ;;
  aarch64) BINARY="malairte-node-linux-arm64"  ;;
  *) echo -e "${RED}Unsupported architecture: $ARCH${NC}"; exit 1 ;;
esac

echo "Detected: Linux $ARCH"
echo ""

echo "→ Downloading $BINARY..."
curl -fsSL "$BASE_URL/$BINARY" -o "$INSTALL_DIR/malairte-node"
chmod +x "$INSTALL_DIR/malairte-node"
echo -e "${GREEN}✓ malairte-node installed to $INSTALL_DIR/malairte-node${NC}"

CLIBINARY="malairte-cli-linux-${ARCH/x86_64/amd64}"
CLIBINARY="${CLIBINARY/aarch64/arm64}"
echo "→ Downloading $CLIBINARY..."
curl -fsSL "$BASE_URL/$CLIBINARY" -o "$INSTALL_DIR/malairte-cli"
chmod +x "$INSTALL_DIR/malairte-cli"
echo -e "${GREEN}✓ malairte-cli installed to $INSTALL_DIR/malairte-cli${NC}"

echo "→ Creating data directory..."
mkdir -p "$DATA_DIR/mainnet/chaindata"
echo -e "${GREEN}✓ Data directory: $DATA_DIR${NC}"

echo "→ Writing systemd service..."
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=Malairte Blockchain Node
After=network.target

[Service]
ExecStart=$INSTALL_DIR/malairte-node --data-dir=$DATA_DIR --network=mainnet --mine --miner-key=$MINER_KEY --seeds=104.192.5.197:9333
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
echo -e "${GREEN}✓ Service file written to $SERVICE_FILE${NC}"

echo "→ Enabling and starting service..."
systemctl daemon-reload
systemctl enable malairte-node
systemctl start malairte-node
echo -e "${GREEN}✓ malairte-node service started${NC}"

echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}  Malairte node is mining! 🎉${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "  Check status:  systemctl status malairte-node"
echo "  View logs:     journalctl -u malairte-node -f"
echo "  RPC:           curl -s -X POST http://127.0.0.1:9332 \\"
echo "                   -H 'Content-Type: application/json' \\"
echo "                   -d '{\"method\":\"getblockchaininfo\",\"id\":1}'"
echo ""
