#!/bin/bash

# Set version number
VERSION=1.1.0  &>/dev/null

# Set temporary and installation directories
TMP_DIR=/tmp/nvidia_gpu_exporter_install &>/dev/null
INSTALL_DIR=/usr/bin &>/dev/null

# Create temporary directory
mkdir -p $TMP_DIR &>/dev/null
# Download and extract nvidia_gpu_exporter
wget -P $TMP_DIR https://github.com/utkuozdemir/nvidia_gpu_exporter/releases/download/v${VERSION}/nvidia_gpu_exporter_${VERSION}_linux_x86_64.tar.gz &>/dev/null
tar -xvzf $TMP_DIR/nvidia_gpu_exporter_${VERSION}_linux_x86_64.tar.gz -C $TMP_DIR &>/dev/null

# Create installation directory and move binary
mkdir -p $INSTALL_DIR &>/dev/null
mv $TMP_DIR/nvidia_gpu_exporter $INSTALL_DIR/ &>/dev/null
chmod +x $INSTALL_DIR/nvidia_gpu_exporter &>/dev/null
# Create system user
useradd --system --no-create-home --shell /usr/sbin/nologin nvidia_gpu_exporter &>/dev/null

# Create systemd service file
cat <<EOF | tee /etc/systemd/system/nvidia_gpu_exporter.service &>/dev/null
[Unit]
Description=Nvidia GPU Exporter
After=network-online.target

[Service]
Type=simple
User=nvidia_gpu_exporter
Group=nvidia_gpu_exporter
ExecStart=$INSTALL_DIR/nvidia_gpu_exporter
SyslogIdentifier=nvidia_gpu_exporter
Restart=always
RestartSec=1

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd and enable service
systemctl daemon-reload &>/dev/null
systemctl enable --now nvidia_gpu_exporter &>/dev/null

if systemctl is-active --quiet nvidia_gpu_exporter; then
    echo "nvidia_gpu_exporter is running"
    exit 0
else
    echo "nvidia_gpu_exporter not running"
    exit 1
fi

