#!/usr/bin/env bash

TEMP_PATH=$(mktemp -d)
NAME=node_exporter
BIN_PATH=/usr/local/bin
OWNER=${1:-nobody}
VERSION="1.6.1"

sed -n -e '1,/^exit 0$/!p' $0 > ${TEMP_PATH}/${NAME}-${VERSION}.tar.gz 2>/dev/null

cd ${TEMP_PATH}

tar axvf ${NAME}-${VERSION}.tar.gz -C /usr/local/bin >/dev/null

if [[ "OWNER" != "nobody" ]]
then
    getent passwd ${ONWER} || useradd -s /sbin/nologin -d /dev/null ${OWNER}
fi

cat >/etc/systemd/system/${NAME}.service<<EOF
[Unit]
Description=Prometheus mysql Exporter
After=network-online.target
StartLimitInterval=0
StartLimitIntervalSec=0

[Service]
Type=simple
User=${OWNER}
Group=${OWNER}
ExecStart=${BIN_PATH}/node_exporter --web.listen-address 0.0.0.0:9100
SyslogIdentifier=${NAME}
Restart=always
RestartSec=5
LockPersonality=true
NoNewPrivileges=true
MemoryDenyWriteExecute=true
PrivateTmp=true
ProtectHome=true
RemoveIPC=true
RestrictSUIDSGID=true
ProtectSystem=full

[Install]
WantedBy=multi-user.target
EOF

rm -rf ${TEMP_PATH}

systemctl enable ${NAME}.service --now

exit 0
