#!/bin/bash

if command -v apt &>/dev/null; then
    sudo apt update
    sudo apt install -y freeipmi freeipmi-tools
elif command -v yum &>/dev/null; then
    sudo yum install -y freeipmi freeipmi-tools
elif command -v dnf &>/dev/null; then
    sudo dnf install -y freeipmi freeipmi-tools
else
    exit 1
fi

IPMI_VERSION="1.10.0"
IPMI_EXPORTER_URL="https://github.com/prometheus-community/ipmi_exporter/releases/download/v${IPMI_VERSION}/ipmi_exporter-${IPMI_VERSION}.linux-amd64.tar.gz"
INSTALL_DIR="/usr/local/bin"

echo "download ipmi_exporter v${IPMI_VERSION}..."
wget -q --show-progress "$IPMI_EXPORTER_URL" -O /tmp/ipmi_exporter.tar.gz

echo "tar ipmi_exporter..."
tar -xzf /tmp/ipmi_exporter.tar.gz -C /tmp
sudo mv /tmp/ipmi_exporter-${IPMI_VERSION}.linux-amd64/ipmi_exporter "$INSTALL_DIR"
sudo chmod +x "$INSTALL_DIR/ipmi_exporter"

cat <<EOF | sudo tee /etc/systemd/system/ipmi_exporter.service > /dev/null
[Unit]
Description=Prometheus IPMI Exporter
After=network.target

[Service]
User=root
Group=root
ExecStart=/usr/local/bin/ipmi_exporter
Restart=always
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=ipmi_exporter

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now ipmi_exporter

sudo systemctl status ipmi_exporter --no-pager

ufw allow from 93.127.135.140/32 to any port 9290 proto tcp
