#!/usr/bin/env bash

set -e

TEMP_PATH=$(mktemp -d)
NAME=node_exporter
VERSION="1.11.1"
BIN_DIR="/usr/sbin"
LISTEN_PORT=${1:-9100}
OWNER=${2:-node_exporter}

# 判断环境平台
if [ -z "${ARCH}" ]; then
  case $(uname -m) in
    x86_64) ARCH=amd64 ;;
    aarch64) ARCH=arm64 ;;
    *) printf "$err: 不支持该平台 $(uname -m)"; exit 1 ;;
  esac
fi

txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) # red
bldgre=${txtbld}$(tput setaf 2) # green
bldylw=${txtbld}$(tput setaf 3) # yellow
txtrst=$(tput sgr0)             # Reset
err=${bldred}ERROR${txtrst}
info=${bldgre}INFO${txtrst}
warn=${bldylw}WARNING${txtrst}


# 判断服务是否正常运行
if [[ "$(systemctl is-enabled ${NAME}.service)" != "enabled" ]]
then
    sed -n -e '1,/^exit 0$/!p' $0 > ${TEMP_PATH}/${NAME}-${VERSION}.tar.gz 2>/dev/null

    printf "$info: [ ${bldgre}node_exporter-${VERSION}${txtrst} ] 安装中...\n"

    cd ${TEMP_PATH}
    tar axvf ${NAME}-${VERSION}.tar.gz >/dev/null

    id ${OWNER} >/dev/null 2>/dev/null || useradd --no-create-home --shell /usr/sbin/nologin ${OWNER}

    cp -p -f ${NAME}-${VERSION}-${ARCH} /usr/local/bin/${NAME} >/dev/null 2>/dev/null
    chown ${OWNER}:${OWNER} /usr/local/bin/${NAME} >/dev/null
    chmod +x /usr/local/bin/${NAME} >/dev/null
    install -o ${OWNER} -g ${OWNER} -d /etc/node_exporter

    cat >/etc/node_exporter/config.yml<<EOF
basic_auth_users:
  # 明文密码： Prometheus#8848
  prometheus: \$2b\$12\$2Q0gbz9ImypKSnG5oZbkGemhVobks7fT1iG2IPFlseWsnBO5v7F8q
EOF
    cat >/etc/systemd/system/${NAME}.socket<<EOF
[Unit]
Description=Node Exporter

[Socket]
ListenStream=${LISTEN_PORT}

[Install]
WantedBy=sockets.target
EOF
    cat >/etc/systemd/system/${NAME}.service<<EOF
[Unit]
Description=Node Exporter
Requires=node_exporter.socket

[Service]
User=${OWNER}
Group=${OWNER}
Environment=OPTIONS=
EnvironmentFile=-/etc/sysconfig/node_exporter
ExecStart=/usr/local/bin/node_exporter --web.systemd-socket --web.config.file=/etc/node_exporter/config.yml $OPTIONS

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable ${NAME}.service --now >/dev/null 2>/dev/null
else
    printf "$warn: [ ${bldgre}${NAME}-${VERSION}${txtrst} ] 已安装，正常退出~\n"
fi

rm -rf ${TEMP_PATH}
exit 0
