#!/bin/bash
#############################################################
#### Nagios Core Installer                               ####
#### Automated source compilation of Nagios Core,        ####
#### plugins, web server config, and systemd setup       ####
####                                                     ####
#### Author: Phil Connor                                 ####
#### Contact: contact@mylinux.work                       ####
#### License: MIT                                        ####
#### Version: 2.0                                        ####
####                                                     ####
#### Usage: ./nagios-core-installer.sh [OPTIONS]         ####
#############################################################
#
# Supported operating systems:
#   - Ubuntu 20.04, 22.04, 24.04
#   - Debian 11, 12
#   - RHEL 8, 9
#   - Rocky Linux 8, 9
#   - Alma Linux 8, 9
#
# What this script does:
#   1. Installs build dependencies
#   2. Creates nagios user and nagcmd group
#   3. Downloads and compiles Nagios Core from source
#   4. Downloads and compiles Nagios Plugins
#   5. Configures Apache or Nginx with authentication
#   6. Optionally installs NRPE daemon
#   7. Enables and starts the systemd service
#   8. Validates configuration
#
set -euo pipefail

#########################
### Configuration ###
#########################

NAGIOS_VERSION="${NAGIOS_VERSION:-4.5.9}"
PLUGINS_VERSION="${PLUGINS_VERSION:-2.4.12}"
NRPE_VERSION="${NRPE_VERSION:-4.1.3}"
WEBSERVER="${WEBSERVER:-apache}"
NAGIOS_ADMIN_USER="${NAGIOS_ADMIN_USER:-nagiosadmin}"
NAGIOS_ADMIN_PASS=""
INSTALL_NRPE=false
NAGIOS_HOME="/usr/local/nagios"
BUILD_DIR="/tmp/nagios-build"

#########################
### Logging ###
#########################

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

#########################
### Parse Arguments ###
#########################

show_help() {
    cat <<EOF
Nagios Core Installer — Source Compilation

Usage: $0 [OPTIONS]

OPTIONS:
  --version VERSION       Nagios Core version (default: $NAGIOS_VERSION)
  --plugins VERSION       Nagios Plugins version (default: $PLUGINS_VERSION)
  --webserver TYPE        Web server: apache or nginx (default: apache)
  --admin-user USER       Web admin username (default: nagiosadmin)
  --admin-pass PASS       Web admin password (prompted if not set)
  --with-nrpe             Also install NRPE server components
  --nrpe-version VERSION  NRPE version (default: $NRPE_VERSION)
  --help                  Show this help

EXAMPLES:
  $0                                      # Install with defaults (Apache)
  $0 --webserver nginx                    # Install with Nginx
  $0 --version 4.5.9 --with-nrpe         # Specific version + NRPE
  $0 --admin-user admin --admin-pass s3cr3t

EOF
    exit 0
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --version)       NAGIOS_VERSION="$2"; shift 2 ;;
            --plugins)       PLUGINS_VERSION="$2"; shift 2 ;;
            --webserver)     WEBSERVER="$2"; shift 2 ;;
            --admin-user)    NAGIOS_ADMIN_USER="$2"; shift 2 ;;
            --admin-pass)    NAGIOS_ADMIN_PASS="$2"; shift 2 ;;
            --with-nrpe)     INSTALL_NRPE=true; shift ;;
            --nrpe-version)  NRPE_VERSION="$2"; shift 2 ;;
            --help)          show_help ;;
            *)               log_error "Unknown option: $1"; exit 1 ;;
        esac
    done

    if [[ "$WEBSERVER" != "apache" && "$WEBSERVER" != "nginx" ]]; then
        log_error "Invalid webserver: $WEBSERVER (must be apache or nginx)"
        exit 1
    fi
}

#########################
### OS Detection ###
#########################

detect_os() {
    if [[ ! -f /etc/os-release ]]; then
        log_error "Cannot detect OS — /etc/os-release not found"
        exit 1
    fi

    # shellcheck disable=SC1091
    source /etc/os-release

    OS_ID="${ID,,}"
    OS_VERSION="${VERSION_ID%%.*}"

    case "$OS_ID" in
        ubuntu|debian)
            OS_FAMILY="debian"
            PKG_MGR="apt-get"
            ;;
        rhel|rocky|almalinux|centos)
            OS_FAMILY="rhel"
            PKG_MGR="dnf"
            ;;
        *)
            log_error "Unsupported OS: $OS_ID"
            exit 1
            ;;
    esac

    log_info "Detected OS: $PRETTY_NAME ($OS_FAMILY family)"
}

#########################
### Pre-flight ###
#########################

check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script must be run as root"
        exit 1
    fi
}

prompt_password() {
    if [[ -z "$NAGIOS_ADMIN_PASS" ]]; then
        echo -n "Enter password for web admin user '$NAGIOS_ADMIN_USER': "
        read -rs NAGIOS_ADMIN_PASS
        echo
        if [[ -z "$NAGIOS_ADMIN_PASS" ]]; then
            log_error "Password cannot be empty"
            exit 1
        fi
    fi
}

#########################
### Dependencies ###
#########################

install_dependencies() {
    log_step "Installing build dependencies..."

    if [[ "$OS_FAMILY" == "debian" ]]; then
        apt-get update -qq
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
            autoconf gcc make unzip wget curl \
            libgd-dev libssl-dev libperl-dev \
            apache2-utils openssl
        if [[ "$WEBSERVER" == "apache" ]]; then
            DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
                apache2 libapache2-mod-php php
        else
            DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
                nginx php-fpm fcgiwrap
        fi
    else
        $PKG_MGR install -y -q \
            autoconf gcc gcc-c++ make unzip wget curl \
            gd-devel openssl-devel perl-devel \
            httpd-tools openssl
        if [[ "$WEBSERVER" == "apache" ]]; then
            $PKG_MGR install -y -q httpd php
        else
            $PKG_MGR install -y -q nginx php-fpm fcgiwrap
        fi
    fi

    log_info "Dependencies installed"
}

#########################
### User Setup ###
#########################

create_nagios_user() {
    log_step "Creating nagios user and nagcmd group..."

    if ! getent group nagcmd &>/dev/null; then
        groupadd nagcmd
        log_info "Created group: nagcmd"
    fi

    if ! id nagios &>/dev/null; then
        useradd -r -g nagcmd -d "$NAGIOS_HOME" -s /bin/false nagios
        log_info "Created user: nagios"
    fi

    # Add web server user to nagcmd group
    local www_user
    if [[ "$OS_FAMILY" == "debian" ]]; then
        www_user="www-data"
    else
        www_user="apache"
        [[ "$WEBSERVER" == "nginx" ]] && www_user="nginx"
    fi

    usermod -aG nagcmd "$www_user" 2>/dev/null || true
    usermod -aG nagcmd nagios 2>/dev/null || true

    log_info "User setup complete"
}

#########################
### Compile Nagios ###
#########################

compile_nagios() {
    log_step "Downloading and compiling Nagios Core $NAGIOS_VERSION..."

    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"

    local tarball="nagios-${NAGIOS_VERSION}.tar.gz"
    local url="https://github.com/NagiosEnterprises/nagioscore/releases/download/nagios-${NAGIOS_VERSION}/${tarball}"

    if [[ ! -f "$tarball" ]]; then
        wget -q "$url" -O "$tarball"
    fi

    tar xzf "$tarball"
    cd "nagios-${NAGIOS_VERSION}"

    ./configure --with-command-group=nagcmd \
        --with-httpd-conf=/etc/apache2/sites-enabled \
        --with-nagios-user=nagios \
        --with-nagios-group=nagcmd \
        > /dev/null 2>&1

    make all > /dev/null 2>&1
    make install > /dev/null 2>&1
    make install-init > /dev/null 2>&1
    make install-commandmode > /dev/null 2>&1
    make install-config > /dev/null 2>&1

    if [[ "$WEBSERVER" == "apache" ]]; then
        make install-webconf > /dev/null 2>&1
    fi

    log_info "Nagios Core $NAGIOS_VERSION compiled and installed to $NAGIOS_HOME"
}

#########################
### Compile Plugins ###
#########################

compile_plugins() {
    log_step "Downloading and compiling Nagios Plugins $PLUGINS_VERSION..."

    cd "$BUILD_DIR"

    local tarball="nagios-plugins-${PLUGINS_VERSION}.tar.gz"
    local url="https://github.com/nagios-plugins/nagios-plugins/releases/download/release-${PLUGINS_VERSION}/${tarball}"

    if [[ ! -f "$tarball" ]]; then
        wget -q "$url" -O "$tarball"
    fi

    tar xzf "$tarball"
    cd "nagios-plugins-${PLUGINS_VERSION}"

    ./configure --with-nagios-user=nagios --with-nagios-group=nagcmd \
        > /dev/null 2>&1

    make > /dev/null 2>&1
    make install > /dev/null 2>&1

    log_info "Nagios Plugins $PLUGINS_VERSION compiled and installed"
}

#########################
### Web Server Config ###
#########################

configure_apache() {
    log_step "Configuring Apache for Nagios..."

    if [[ "$OS_FAMILY" == "debian" ]]; then
        a2enmod rewrite cgi 2>/dev/null || true

        cat > /etc/apache2/sites-enabled/nagios.conf <<'APACHECONF'
ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin"
Alias /nagios "/usr/local/nagios/share"

<Directory "/usr/local/nagios/sbin">
    Options ExecCGI
    AllowOverride None
    AuthType Basic
    AuthName "Nagios Access"
    AuthUserFile /usr/local/nagios/etc/htpasswd.users
    Require valid-user
</Directory>

<Directory "/usr/local/nagios/share">
    Options None
    AllowOverride None
    AuthType Basic
    AuthName "Nagios Access"
    AuthUserFile /usr/local/nagios/etc/htpasswd.users
    Require valid-user
</Directory>
APACHECONF
    else
        cat > /etc/httpd/conf.d/nagios.conf <<'APACHECONF'
ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin"
Alias /nagios "/usr/local/nagios/share"

<Directory "/usr/local/nagios/sbin">
    Options ExecCGI
    AllowOverride None
    AuthType Basic
    AuthName "Nagios Access"
    AuthUserFile /usr/local/nagios/etc/htpasswd.users
    Require valid-user
</Directory>

<Directory "/usr/local/nagios/share">
    Options None
    AllowOverride None
    AuthType Basic
    AuthName "Nagios Access"
    AuthUserFile /usr/local/nagios/etc/htpasswd.users
    Require valid-user
</Directory>
APACHECONF
    fi

    log_info "Apache configured"
}

configure_nginx() {
    log_step "Configuring Nginx for Nagios..."

    local php_sock
    if [[ "$OS_FAMILY" == "debian" ]]; then
        php_sock=$(find /var/run/php/ -name "php*-fpm.sock" 2>/dev/null | head -1)
        [[ -z "$php_sock" ]] && php_sock="/var/run/php/php-fpm.sock"
    else
        php_sock="/run/php-fpm/www.sock"
    fi

    cat > /etc/nginx/conf.d/nagios.conf <<NGINXCONF
server {
    listen 80;
    server_name _;

    root ${NAGIOS_HOME}/share;
    index index.php index.html;

    auth_basic "Nagios Access";
    auth_basic_user_file ${NAGIOS_HOME}/etc/htpasswd.users;

    location /nagios {
        alias ${NAGIOS_HOME}/share;
    }

    location ~ \.cgi\$ {
        root ${NAGIOS_HOME}/sbin;
        rewrite ^/nagios/cgi-bin/(.*)\$ /\$1;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param AUTH_USER \$remote_user;
        fastcgi_param REMOTE_USER \$remote_user;
        fastcgi_pass unix:/var/run/fcgiwrap.socket;
    }

    location ~ \.php\$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_pass unix:${php_sock};
    }
}
NGINXCONF

    log_info "Nginx configured"
}

configure_webserver() {
    if [[ "$WEBSERVER" == "apache" ]]; then
        configure_apache
    else
        configure_nginx
    fi

    # Create htpasswd file
    htpasswd -cb "$NAGIOS_HOME/etc/htpasswd.users" "$NAGIOS_ADMIN_USER" "$NAGIOS_ADMIN_PASS"
    chown nagios:nagcmd "$NAGIOS_HOME/etc/htpasswd.users"
    chmod 640 "$NAGIOS_HOME/etc/htpasswd.users"

    log_info "Web admin user '$NAGIOS_ADMIN_USER' created"
}

#########################
### NRPE Install ###
#########################

install_nrpe() {
    if [[ "$INSTALL_NRPE" != "true" ]]; then
        return
    fi

    log_step "Installing NRPE $NRPE_VERSION..."

    cd "$BUILD_DIR"

    local tarball="nrpe-${NRPE_VERSION}.tar.gz"
    local url="https://github.com/NagiosEnterprises/nrpe/releases/download/nrpe-${NRPE_VERSION}/${tarball}"

    if [[ ! -f "$tarball" ]]; then
        wget -q "$url" -O "$tarball"
    fi

    tar xzf "$tarball"
    cd "nrpe-${NRPE_VERSION}"

    ./configure --with-nagios-user=nagios --with-nagios-group=nagcmd \
        --enable-command-args > /dev/null 2>&1

    make all > /dev/null 2>&1
    make install > /dev/null 2>&1
    make install-config > /dev/null 2>&1
    make install-init > /dev/null 2>&1

    systemctl enable nrpe
    systemctl start nrpe

    log_info "NRPE $NRPE_VERSION installed and started"
}

#########################
### Systemd Setup ###
#########################

setup_systemd() {
    log_step "Configuring systemd services..."

    systemctl daemon-reload

    # Enable and start Nagios
    systemctl enable nagios
    systemctl start nagios

    # Enable and restart web server
    if [[ "$WEBSERVER" == "apache" ]]; then
        if [[ "$OS_FAMILY" == "debian" ]]; then
            systemctl enable apache2
            systemctl restart apache2
        else
            systemctl enable httpd
            systemctl restart httpd
        fi
    else
        systemctl enable nginx
        systemctl restart nginx
        systemctl enable fcgiwrap 2>/dev/null || true
        systemctl start fcgiwrap 2>/dev/null || true
        systemctl enable php-fpm 2>/dev/null || systemctl enable "php*-fpm" 2>/dev/null || true
        systemctl restart php-fpm 2>/dev/null || systemctl restart "php*-fpm" 2>/dev/null || true
    fi

    log_info "Systemd services enabled and started"
}

#########################
### Validate Config ###
#########################

validate_config() {
    log_step "Validating Nagios configuration..."

    if "$NAGIOS_HOME/bin/nagios" -v "$NAGIOS_HOME/etc/nagios.cfg" > /dev/null 2>&1; then
        log_info "Configuration validation passed"
    else
        log_warn "Configuration validation returned warnings — review with:"
        log_warn "  $NAGIOS_HOME/bin/nagios -v $NAGIOS_HOME/etc/nagios.cfg"
    fi
}

#########################
### Cleanup ###
#########################

cleanup() {
    log_step "Cleaning up build directory..."
    rm -rf "$BUILD_DIR"
    log_info "Build directory removed"
}

#########################
### Summary ###
#########################

show_summary() {
    local ip
    ip=$(hostname -I 2>/dev/null | awk '{print $1}')
    [[ -z "$ip" ]] && ip="<server-ip>"

    echo ""
    echo "============================================="
    echo "  Nagios Core Installation Complete"
    echo "============================================="
    echo ""
    echo "  Nagios Core:    $NAGIOS_VERSION"
    echo "  Plugins:        $PLUGINS_VERSION"
    echo "  Web Server:     $WEBSERVER"
    echo "  Install Path:   $NAGIOS_HOME"
    echo ""
    echo "  Web Interface:  http://${ip}/nagios"
    echo "  Username:       $NAGIOS_ADMIN_USER"
    echo ""
    if [[ "$INSTALL_NRPE" == "true" ]]; then
        echo "  NRPE:           $NRPE_VERSION (installed)"
    fi
    echo ""
    echo "  Config dir:     $NAGIOS_HOME/etc/"
    echo "  Validate:       $NAGIOS_HOME/bin/nagios -v $NAGIOS_HOME/etc/nagios.cfg"
    echo "  Service:        systemctl status nagios"
    echo ""
    echo "============================================="
}

#########################
### Main ###
#########################

main() {
    parse_args "$@"
    check_root
    detect_os
    prompt_password
    install_dependencies
    create_nagios_user
    compile_nagios
    compile_plugins
    configure_webserver
    install_nrpe
    setup_systemd
    validate_config
    cleanup
    show_summary
}

main "$@"
