#!/usr/bin/env bash
set -euo pipefail
INSTALL_DIR=/opt/node_exporter
USER=node_exporter
PORT=9100
TAR="node_exporter-1.9.1.linux-amd64.tar.gz"
URL="https://files.wanghaoyu.me/prometheus/node_exporter/v1.9.1/${TAR}"
SERVICE=/etc/systemd/system/node_exporter.service

[[ $EUID -eq 0 ]] || { echo "Run as root"; exit 1; }

if command -v apt-get &>/dev/null; then
  apt-get update -qq && apt-get install -y wget tar
elif command -v yum &>/dev/null; then
  yum install -y wget tar
elif command -v dnf &>/dev/null; then
  dnf install -y wget tar
fi

id -u $USER &>/dev/null || useradd --system -s /sbin/nologin -M $USER

mkdir -p $INSTALL_DIR
cd /tmp
wget -qO $TAR $URL
tar -xzf $TAR --strip-components=1 -C $INSTALL_DIR
rm -f $TAR
chown -R $USER:$USER $INSTALL_DIR
chmod +x $INSTALL_DIR/node_exporter

# systemd
cat >$SERVICE <<EOF
[Unit]
Description=Prometheus Node Exporter
After=network-online.target
[Service]
User=$USER
ExecStart=$INSTALL_DIR/node_exporter --web.listen-address=:$PORT
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now node_exporter

if command -v firewall-cmd &>/dev/null; then
  firewall-cmd --permanent --add-port=$PORT/tcp && firewall-cmd --reload
elif command -v ufw &>/dev/null; then
  ufw allow $PORT/tcp
fi

if systemctl -q is-active node_exporter; then
  IP=$(hostname -I | awk '{print $1}')
  echo "Node Exporter is running."
  echo "Local:  http://127.0.0.1:$PORT/metrics"
  echo "Public: http://$IP:$PORT/metrics"
else
  echo "Start failed"; journalctl -u node_exporter -n 30; exit 1
fi
