#!/bin/bash
#
# setup_nagios.sh
# Installs and configures Nagios Core + Nagios Plugins + NRPE on
# Debian/Ubuntu based systems.
#
# Usage:
#   sudo ./setup_nagios.sh
#
# After running, Nagios web UI will be available at:
#   http://<server-ip>/nagios
#
# Tested target: Ubuntu 20.04/22.04/24.04, Debian 11/12
#

set -euo pipefail

# ---------- Config (edit as needed) ----------
NAGIOS_VERSION="4.4.14"
PLUGINS_VERSION="2.4.9"
NAGIOSADMIN_PASSWORD="ChangeMe123!"   # CHANGE THIS before running
INSTALL_DIR="/usr/local/nagios"
WEB_SERVER="apache2"                  # apache2 is used below
# ------------------------------------------------

log() {
    echo -e "\n\033[1;32m==> $1\033[0m\n"
}

require_root() {
    if [[ $EUID -ne 0 ]]; then
        echo "This script must be run as root (use sudo)." >&2
        exit 1
    fi
}

require_root

log "Updating package lists and installing prerequisites"
apt-get update -y
apt-get install -y \
    wget curl unzip \
    build-essential \
    "$WEB_SERVER" php libapache2-mod-php \
    php-gd \
    libgd-dev \
    openssl libssl-dev \
    daemon \
    autoconf gcc make \
    unzip

log "Creating nagios user and nagcmd group"
if ! id nagios &>/dev/null; then
    useradd -m -s /bin/bash nagios
fi
if ! getent group nagcmd &>/dev/null; then
    groupadd nagcmd
fi
usermod -a -G nagcmd nagios
usermod -a -G nagcmd www-data

log "Downloading Nagios Core ${NAGIOS_VERSION}"
cd /tmp
rm -rf nagios-build && mkdir nagios-build && cd nagios-build
wget -q "https://assets.nagios.com/downloads/nagioscore/releases/nagios-${NAGIOS_VERSION}.tar.gz"
tar xzf "nagios-${NAGIOS_VERSION}.tar.gz"
cd "nagios-${NAGIOS_VERSION}"

log "Compiling and installing Nagios Core"
./configure --with-command-group=nagcmd --with-httpd-conf=/etc/apache2/sites-enabled
make all
make install
make install-init
make install-commandmode
make install-config
make install-webconf

log "Downloading and installing Nagios Plugins ${PLUGINS_VERSION}"
cd /tmp/nagios-build
wget -q "https://nagios-plugins.org/download/nagios-plugins-${PLUGINS_VERSION}.tar.gz"
tar xzf "nagios-plugins-${PLUGINS_VERSION}.tar.gz"
cd "nagios-plugins-${PLUGINS_VERSION}"
./configure --with-nagios-user=nagios --with-nagios-group=nagios
make
make install

log "Enabling Apache modules and Nagios site"
a2enmod rewrite cgi

# install-webconf (via --with-httpd-conf=/etc/apache2/sites-enabled) drops
# the vhost config straight into sites-enabled, so there's nothing to
# "enable" with a2ensite. Just confirm it landed there.
NAGIOS_APACHE_CONF="/etc/apache2/sites-enabled/nagios.conf"
if [[ -f "$NAGIOS_APACHE_CONF" ]]; then
    echo "Nagios Apache config found at ${NAGIOS_APACHE_CONF}"
else
    echo "WARNING: ${NAGIOS_APACHE_CONF} not found." >&2
    echo "Check that 'make install-webconf' completed successfully." >&2
fi

# The shipped nagios.conf uses old Apache 2.2 syntax
# (Order allow,deny / Allow from all), which Apache 2.4 ignores by
# default and results in "Forbidden: You don't have permission to
# access this resource." Fix it two ways for safety:
#
# 1) Enable mod_access_compat so the old directives still work.
# 2) Explicitly add "Require all granted" to each <Directory> block
#    in case access_compat isn't available/enabled.
log "Applying Apache 2.4 compatibility fix for Nagios config"
a2enmod access_compat || true

if [[ -f "$NAGIOS_APACHE_CONF" ]] && ! grep -q "Require all granted" "$NAGIOS_APACHE_CONF"; then
    # Insert "Require all granted" right after every "<Directory ...>" line
    # that doesn't already have it, using a temp file for portability.
    awk '
        { print }
        /<Directory / && $0 !~ /Require all granted/ {
            print "        Require all granted"
        }
    ' "$NAGIOS_APACHE_CONF" > "${NAGIOS_APACHE_CONF}.tmp" && mv "${NAGIOS_APACHE_CONF}.tmp" "$NAGIOS_APACHE_CONF"
    echo "Inserted 'Require all granted' into ${NAGIOS_APACHE_CONF}"
fi

log "Creating nagiosadmin web user"
htpasswd -b -c "${INSTALL_DIR}/etc/htpasswd.users" nagiosadmin "${NAGIOSADMIN_PASSWORD}"

log "Verifying Nagios configuration"
"${INSTALL_DIR}/bin/nagios" -v "${INSTALL_DIR}/etc/nagios.cfg"

log "Enabling and starting services"
systemctl enable nagios
systemctl restart nagios
systemctl restart "$WEB_SERVER"

log "Setup complete!"

# Try to detect the server's public/primary IP for a friendlier final message.
SERVER_IP="$(curl -s -4 --max-time 3 ifconfig.me || true)"
if [[ -z "$SERVER_IP" ]]; then
    SERVER_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
fi
if [[ -z "$SERVER_IP" ]]; then
    SERVER_IP="<server-ip>"
fi

echo "Nagios web UI: http://${SERVER_IP}/nagios"
echo "Login user:    nagiosadmin"
echo "Login pass:    ${NAGIOSADMIN_PASSWORD}  (change this in the script before running in production)"
echo
echo "Config files live in: ${INSTALL_DIR}/etc/"
echo "Add new host/service checks under: ${INSTALL_DIR}/etc/objects/"
echo "After editing configs, verify with:"
echo "    ${INSTALL_DIR}/bin/nagios -v ${INSTALL_DIR}/etc/nagios.cfg"
echo "Then reload with:"
echo "    systemctl restart nagios"