#!/bin/bash

# Function to install node_exporter
install_node_exporter() {
    # Create a user for node_exporter
    sudo useradd -rs /bin/false node_exporter
    echo "User 'node_exporter' created."

    # Create a directory for node_exporter
    sudo mkdir -p /opt/node_exporter
    echo "Directory '/opt/node_exporter' created."

    # Move the downloaded binary to the appropriate directory
    EXTRACTED_DIR="node_exporter-${LATEST_VERSION#v}.linux-amd64"
    if [ -f "${EXTRACTED_DIR}/node_exporter" ]; then
        sudo mv "${EXTRACTED_DIR}/node_exporter" /usr/local/bin/
        echo "Node Exporter binary moved to /usr/local/bin."
    else
        echo "Node Exporter binary not found in the extracted directory."
        exit 1
    fi

    # Set ownership and permissions
    sudo chown node_exporter:node_exporter /usr/local/bin/node_exporter
    echo "Ownership set for /usr/local/bin/node_exporter."

    sudo chmod 755 /usr/local/bin/node_exporter
    echo "Permissions set for /usr/local/bin/node_exporter."
}

# Function to create a systemd service for node_exporter
create_service() {
    # Create a systemd service file
    cat <<EOF | sudo tee /etc/systemd/system/node_exporter.service
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target

[Service]
User=node_exporter
ExecStart=/usr/local/bin/node_exporter
Restart=on-failure

[Install]
WantedBy=default.target
EOF
    echo "Systemd service file created at /etc/systemd/system/node_exporter.service."

    # Reload systemd to recognize the new service
    sudo systemctl daemon-reload
    echo "Systemd daemon reloaded."

    # Start and enable the node_exporter service
    sudo systemctl start node_exporter
    if [ $? -eq 0 ]; then
        echo "Node Exporter service started."
    else
        echo "Failed to start Node Exporter service."
        exit 1
    fi

    sudo systemctl enable node_exporter
    echo "Node Exporter service enabled to start on boot."

    echo "Node Exporter service created and running."
}

# Function to check the status of node_exporter service
check_service_status() {
    if systemctl is-active --quiet node_exporter; then
        echo "Node Exporter service is active and running."
        return 0
    else
        echo "Node Exporter service is not running."
        echo "You can check the logs with: sudo journalctl -u node_exporter.service"
        return 1
    fi
}

# Function to clean up downloaded files
cleanup_files() {
    if [[ -f "node_exporter-${LATEST_VERSION#v}.linux-amd64.tar.gz" ]]; then
        rm -rf node_exporter-${LATEST_VERSION#v}.linux-amd64.tar.gz
        echo "Cleaned up downloaded files."
    fi
    if [[ -d "node_exporter-${LATEST_VERSION#v}.linux-amd64" ]]; then
        rm -rf node_exporter-${LATEST_VERSION#v}.linux-amd64
        echo "Cleaned up extracted files."
    fi
}

# Function to display the menu
display_menu() {
    echo "=============================="
    echo " Node Exporter Management Menu "
    echo "=============================="
    echo "1. Install Node Exporter"
    echo "2. Create Node Exporter Service"
    echo "3. Check Node Exporter Service Status"
    echo "4. Clean Up Downloaded Files"
    echo "5. Run All Options"
    echo "6. Exit"
    echo "=============================="
}

# Identify the Linux distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
else
    echo "Unsupported OS"
    exit 1
fi

# Download the latest version of node_exporter
LATEST_VERSION=$(curl -s https://api.github.com/repos/prometheus/node_exporter/releases/latest | grep -oP '"tag_name": "\K(.*)(?=")')
DOWNLOAD_URL="https://github.com/prometheus/node_exporter/releases/download/${LATEST_VERSION}/node_exporter-${LATEST_VERSION#v}.linux-amd64.tar.gz"

# Download node_exporter
echo "Downloading Node Exporter version ${LATEST_VERSION}..."
curl -LO ${DOWNLOAD_URL}

# Check if the download was successful
if [ $? -ne 0 ]; then
    echo "Error downloading Node Exporter. Please check the URL."
    exit 1
fi

# Check if the downloaded file exists
if [ ! -f "node_exporter-${LATEST_VERSION#v}.linux-amd64.tar.gz" ]; then
    echo "Downloaded file does not exist."
    exit 1
fi

# Extract node_exporter
tar -xzf node_exporter-${LATEST_VERSION#v}.linux-amd64.tar.gz
if [ $? -eq 0 ]; then
    echo "Node Exporter extracted successfully."
else
    echo "Error extracting Node Exporter. Please check the downloaded file."
    exit 1
fi

# Main menu loop
while true; do
    display_menu
    read -p "Select an option [1-6]: " option

    case $option in
        1)
            install_node_exporter
            ;;
        2)
            create_service
            ;;
        3)
            check_service_status
            ;;
        4)
            cleanup_files
            ;;
        5)
            install_node_exporter
            create_service
            check_service_status
            read -p "Do you want to clean up the downloaded files? (y/n): " cleanup_choice
            if [[ "$cleanup_choice" == "y" || "$cleanup_choice" == "Y" ]]; then
                cleanup_files
            else
                echo "Downloaded files retained."
            fi
            ;;
        6)
            echo "Exiting."
            exit 0
            ;;
        *)
            echo "Invalid option. Please select a valid option."
            ;;
    esac
done

echo "Script execution completed."
