#!/bin/bash

DOWNLOAD_URL=https://github.com/prometheus/node_exporter/releases/download/v1.0.1/node_exporter-1.0.1.linux-amd64.tar.gz
BIN_PATH="/usr/local/bin/node_exporter"
SERVICE_PATH="/etc/systemd/system/node_exporter.service"
DOWNLOAD_FILE="/opt/node_exporter.tar.gz"

wget -q "$DOWNLOAD_URL" -O "$DOWNLOAD_FILE"
tar -zxvf "$DOWNLOAD_FILE" -C /opt/

mv /opt/node_exporter-1.0.1.linux-amd64/node_exporter "$BIN_PATH"
chmod +x "$BIN_PATH"

cat <<EOF | tee "$SERVICE_PATH"
[Unit]
Description=Node Exporter
Wants=network.target
After=network.target

[Service]
ExecStart=$BIN_PATH
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start node_exporter.service
systemctl enable node_exporter.service

if systemctl is-active --quiet node_exporter; then
    echo "node_exporter is running"
else
    echo "node_exporter not running"
fi
