#!/bin/bash
# install-node-exporter.sh
# Installs Prometheus Node Exporter as a systemd service on any Linux server.
# Usage: bash install-node-exporter.sh [<host>]
#   Without <host>: install locally
#   With <host>: install via SSH (requires root SSH key at ~/.ssh/itpp-infra)

set -euo pipefail

NODE_EXPORTER_VERSION="1.8.2"
ARCH="linux-amd64"

install_local() {
    if systemctl is-active --quiet node_exporter 2>/dev/null; then
        echo "node_exporter already running — skipping install"
        return 0
    fi

    echo "==> Downloading node_exporter ${NODE_EXPORTER_VERSION}..."
    cd /tmp
    wget -q "https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/node_exporter-${NODE_EXPORTER_VERSION}.${ARCH}.tar.gz"
    tar xzf "node_exporter-${NODE_EXPORTER_VERSION}.${ARCH}.tar.gz"

    echo "==> Installing binary..."
    cp "node_exporter-${NODE_EXPORTER_VERSION}.${ARCH}/node_exporter" /usr/local/bin/
    chmod 755 /usr/local/bin/node_exporter

    echo "==> Creating systemd service..."
    cat > /etc/systemd/system/node_exporter.service << 'EOF'
[Unit]
Description=Prometheus Node Exporter
After=network.target

[Service]
Type=simple
User=nobody
Group=nogroup
ExecStart=/usr/local/bin/node_exporter \
  --web.listen-address=:9100 \
  --collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable node_exporter
    systemctl start node_exporter
    systemctl status node_exporter --no-pager -l | head -10

    echo "==> Cleaning up..."
    rm -rf "/tmp/node_exporter-${NODE_EXPORTER_VERSION}.${ARCH}"*

    echo "==> node_exporter installed and running on port 9100"
}

if [ $# -eq 0 ]; then
    install_local
else
    HOST="$1"
    echo "==> Installing node_exporter on ${HOST}..."
    # Copy install script and run remotely
    scp -o StrictHostKeyChecking=no -i ~/.ssh/itpp-infra "$0" "root@${HOST}:/tmp/install-node-exporter.sh"
    ssh -o StrictHostKeyChecking=no -i ~/.ssh/itpp-infra "root@${HOST}" "bash /tmp/install-node-exporter.sh"
    echo "==> node_exporter installed on ${HOST}"
fi
