#!/bin/bash

# 下载 Node Exporter
curl -O http://test.leso114.com:8082/tools/prometheus/node/node_exporter-1.8.2.linux-amd64.tar.gz

# 解压下载的文件
tar -xvf node_exporter-1.8.2.linux-amd64.tar.gz

# 移动解压后的目录到指定路径
mv node_exporter-1.8.2.linux-amd64 /opt/node_exporter

# 更改目录权限
chown root:root -R /opt/node_exporter

# 创建 init.d 脚本
cat << EOF > /etc/init.d/node_exporter
#!/bin/bash
# /etc/init.d/node_exporter

# chkconfig:   2345 99 10
# description: Node Exporter service

NODE_EXPORTER_BINARY="/opt/node_exporter/node_exporter"
PID_FILE="/var/run/node_exporter.pid"

start() {
    echo "Starting node_exporter..."
    if [ -f \$PID_FILE ]; then
        echo "node_exporter is already running."
        return 1
    fi
    nohup \$NODE_EXPORTER_BINARY >> /var/log/node_exporter.log 2>&1 & echo \$! > \$PID_FILE
    echo "node_exporter started."
}

stop() {
    echo "Stopping node_exporter..."
    if [ ! -f \$PID_FILE ]; then
        echo "node_exporter is not running."
        return 1
    fi
    kill \$(cat \$PID_FILE)
    rm -f \$PID_FILE
    echo "node_exporter stopped."
}

case "\$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        if [ -f \$PID_FILE ]; then
            echo "node_exporter is running with PID \$(cat \$PID_FILE)."
        else
            echo "node_exporter is not running."
        fi
        ;;
    *)
        echo "Usage: \$0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
EOF

# 设置权限
chmod +x /etc/init.d/node_exporter

# 将服务添加到系统启动项
chkconfig --add node_exporter

# 启动 Node Exporter 服务
service node_exporter start

# 设置开机启动
chkconfig node_exporter on

# 检查状态
service node_exporter status

# 测试 Node Exporter 是否正常运行
curl http://127.0.0.1:9100

