#!/bin/bash

. ./libinstall.sh

export distro
export dist

# Force the install even if the nagiosna directory exists
FORCE="False"

# Global environment variable that determines whether to prompt the user for various information or not
INTERACTIVE="True"

proddir="/var/www/html/nagiosna"
backenddir="/usr/local/nagiosna"

# INSTALL_PATH is current dir for use in making install dir independent
INSTALL_PATH="$(pwd)"
INSTALLED_FLAG="$backenddir/.installed"
ENV_BACKUP="/store/backups/nagiosna/.nagiosna.env.backup"

IP_ADDRESS="$(hostname -I | awk '{print $1}')"

do_install_check

install_help() {
    cat <<-EOF

        Nagios Network Analyzer Installer
        Copyright 2025-, Nagios Enterprises LLC.
        License:
            Nagios Software License <http://assets.nagios.com/licenses/nagios_software_license.txt>

        Usage: ./fullinstall [options...]

        Options:
            -h | --help
                Display this help text
            -f | --force
                Force install (remove existing installation)
            -n | --non-interactive
                Assume defaults for all questions (for scripted installs)
EOF
}

create_users() {
    echo_c "Setting up permissions..." "$BLUE"
    add_user nna
    add_group nnacmd
    add_to_groups nna nnacmd
}

prereqs() {
    echo_c "Installing packages..." "$BLUE"

    # Shared packages for both distros
    shared_pkgs="php php-cli php-common php-fpm php-opcache supervisor flex bison php-gd php-mbstring php-xml gcc make libtool php-ldap whois curl unzip sysstat acl"
    shared_python_pkgs="python3 python3-pip python3-numpy python3-dateutil"

    if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
        pkgs="apache2 php-mysql mariadb-server mariadb-client libcairo2-dev libglib2.0-dev libxml2-dev libpango1.0-dev libbz2-dev snmp libsnmp-dev php-curl php-zip php-dev cron ldap-utils libldap-common uuid-runtime sudo gnupg"
        python_pkgs="python3-dev default-libmysqlclient-dev python3-mysqldb python3-setuptools"

        apt-get update
        apt-get install $shared_pkgs $pkgs -y 
        apt-get install $shared_python_pkgs $python_pkgs -y
    else
        pkgs="httpd php-mysqlnd cairo-devel glib2-devel libxml2-devel pango-devel bzip2-devel net-snmp-devel php-devel cronie net-snmp net-snmp-utils"
        python_pkgs="python3-devel python3-mysqlclient"

        if [ "$dist" == "el9" ] || [ "$dist" == "el10" ]; then
            # Enable codeready builder repo
            if [ "$distro" == "RedHatEnterpriseServer" ] && [ "$dist" == "el10" ]; then
                yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-10.noarch.rpm
                subscription-manager repos --enable codeready-builder-for-rhel-10-x86_64-rpms
            elif [ "$distro" == "RedHatEnterpriseServer" ] && [ "$dist" == "el9" ]; then
                yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
                subscription-manager repos --enable codeready-builder-for-rhel-9-x86_64-rpms
            elif [ "$distro" == "OracleServer" ] && [ "$dist" == "el9" ]; then
                yum install epel-release -y
                yum config-manager --set-enabled ol9_codeready_builder
            elif [ "$distro" == "OracleServer" ] && [ "$dist" == "el10" ]; then
                yum install oracle-epel-release-el10 -y
                yum config-manager --set-enabled ol10_codeready_builder
            elif [[ "$dist" == "el9" || "$dist" == "el10" ]] && rpm -q centos-stream-release; then
                dnf install epel-release -y
                dnf config-manager --set-enabled crb
            fi
        fi

        if [ "$dist" == "el10" ]; then
            pkgs="$pkgs mysql8.4-server"
        else 
            dnf module enable php:8.2 -y
            pkgs="$pkgs mysql-server"
        fi

        # required for python3-mysqlclient
        dnf install $shared_pkgs $pkgs -y
        dnf install $shared_python_pkgs $python_pkgs -y

        systemctl enable --now crond
    fi

    install_influxdb_python_client
}

nagiosna() {
    echo_c "Setting up the environment..." "$BLUE"

    # If re-installing use the backup .env file
    if [ "$FORCE" = "True" ] && [ -f "$ENV_BACKUP" ]; then
        echo_c "Using backup .env file..." "$BLUE"

        ROOT_MYSQL_PASS=$(read_env_password "$ENV_BACKUP" "DB_ROOT_PASSWORD")
        if [ -z "$ROOT_MYSQL_PASS" ]; then
            echo_c "ERROR: No DB_ROOT_PASSWORD found in $ENV_BACKUP" "$RED"
            exit 1
        fi
        echo_c "Using MySQL root password from backup .env file: $ROOT_MYSQL_PASS" "$ORANGE"

        ROOT_INFLUX_PASS=$(read_env_password "$ENV_BACKUP" "INFLUX_ROOT_PASSWORD")
        if [ -z "$ROOT_INFLUX_PASS" ]; then
            echo_c "ERROR: No INFLUX_ROOT_PASSWORD found in $ENV_BACKUP" "$RED"
            exit 1
        fi
        echo_c "Using InfluxDB root password from backup .env file: $ROOT_INFLUX_PASS" "$ORANGE"

        APP_KEY=$(grep '^APP_KEY=' "$ENV_BACKUP" | cut -d '=' -f2-)
        if [ -z "$APP_KEY" ]; then
            echo_c "ERROR: No APP_KEY found in $ENV_BACKUP" "$RED"
            exit 1
        fi
        echo "Using app key from backup .env file: $APP_KEY"
        export APP_KEY

        APP_UUID=$(grep '^APP_UUID=' "$ENV_BACKUP" | cut -d '=' -f2-)
        if [ -z "$APP_UUID" ]; then
            echo_c "ERROR: No APP_UUID found in $ENV_BACKUP" "$RED"
            exit 1
        fi
        echo "Using app UUID from backup .env file: $APP_UUID"
        export APP_UUID

    # Generate a new MySQL root password
    else
        ROOT_MYSQL_PASS="$(generate_mysql_password)"
        echo_c "The MySQL root password will be: $ROOT_MYSQL_PASS" "$ORANGE"

        ROOT_INFLUX_PASS="$(generate_mysql_password)"
        echo_c "The InfluxDB root password will be: $ROOT_INFLUX_PASS" "$ORANGE"
    fi

    export ROOT_MYSQL_PASS
    export ROOT_INFLUX_PASS

    if [ -z "$NAGIOSNA_MYSQL_PASS" ]; then
		NAGIOSNA_MYSQL_PASS="$(generate_mysql_password)"
        echo_c "The MySQL nagiosna password will be: $NAGIOSNA_MYSQL_PASS" "$ORANGE"
	fi

    if [ -z "$NAGIOSNA_INFLUX_PASS" ]; then
		NAGIOSNA_INFLUX_PASS="$(generate_mysql_password)"
        echo_c "The InfluxDB nagiosna password will be: $NAGIOSNA_INFLUX_PASS" "$ORANGE"
	fi

    export NAGIOSNA_MYSQL_PASS
    export NAGIOSNA_INFLUX_PASS
    export APP_URL="http://$IP_ADDRESS"

    echo_c "Copying application files..." "$BLUE"
    mkdir -p "$proddir"
    cp -r "$INSTALL_PATH/nagiosna" /var/www/html/

    if [ -z "$APP_UUID" ]; then
        APP_UUID=$(uuidgen)
        echo "Generated app UUID: $APP_UUID"
        export APP_UUID
    fi

    envsubst < "$proddir/.env.example" > "$proddir/.env"
    chmod 640 "$proddir/.env"
    chown nna:nnacmd "$proddir/.env"
}

firewall() {
    if [ "$distro" != "Ubuntu" ] && [ "$distro" != "Debian" ]; then
        # Opens default Apache ports and default master port
        open_tcp_ports 80 443 8080
    fi
}

library_path() {
    if [ "$architecture" == "x86_64" ]; then
        echo '/usr/local/lib' >> /etc/ld.so.conf.d/nagiosna.conf
        echo '/usr/local/lib64' >> /etc/ld.so.conf.d/nagiosna.conf
    else
        echo '/usr/local/lib' >> /etc/ld.so.conf.d/nagiosna.conf
    fi
    ldconfig
}

db() {
    if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
        echo_c "Setting up the MariaDB database..." "$BLUE"
    else
        echo_c "Setting up the MySQL database..." "$BLUE"
    fi

    echo "Starting $mysqld..."
    systemctl start $mysqld
    systemctl enable $mysqld

    # If the passwords are not set, load them from the .env file
    if [ -z "$ROOT_MYSQL_PASS" ] && [ -z "$NAGIOSNA_MYSQL_PASS" ]; then
        ROOT_MYSQL_PASS=$(read_env_password "$proddir/.env" "DB_ROOT_PASSWORD")
        if [ -z "$ROOT_MYSQL_PASS" ]; then
            echo_c "ERROR: No DB_ROOT_PASSWORD found in $proddir/.env" "$RED"
            exit 1
        fi
        NAGIOSNA_MYSQL_PASS=$(read_env_password "$proddir/.env" "DB_PASSWORD")
        if [ -z "$NAGIOSNA_MYSQL_PASS" ]; then
            echo_c "ERROR: No DB_PASSWORD found in $proddir/.env" "$RED"
            exit 1
        fi
    fi

    ROOT_MYSQL_PASS_ESC=$(escape_mysql_password "$ROOT_MYSQL_PASS")
    NAGIOSNA_MYSQL_PASS_ESC=$(escape_mysql_password "$NAGIOSNA_MYSQL_PASS")

    unset MYSQL_PWD
    if mysql -u root -e "SELECT 1" &>/dev/null; then
        echo "Connected to database as root."
    elif export MYSQL_PWD="$ROOT_MYSQL_PASS" && mysql -u root -e "SELECT 1" &>/dev/null; then
        echo_c "Database root user already has a password configured." "$ORANGE"
    elif [[ "$dist" == "el9" || "$dist" == "el10" ]]; then
        LOG_PATH="/var/log/mysqld.log"
        TEMP_MYSQL_PASS="$(grep 'temporary password' "$LOG_PATH" | tail -1 | awk '{print $NF}')"
        if [ -n "$TEMP_MYSQL_PASS" ]; then
            echo "Using temporary MySQL root password from log."
            export MYSQL_PWD="$TEMP_MYSQL_PASS"
            if ! mysql -u root -e "SELECT 1" &>/dev/null; then
                echo_c "ERROR: Could not connect with temporary MySQL root password." "$RED"
                exit 1
            fi
        else
            echo_c "ERROR: Could not access the MySQL root user!" "$RED"
            exit 1
        fi
    else
        echo_c "ERROR: Could not access the database root user!" "$RED"
        exit 1
    fi

    DB_EXISTS=$(mysql -sse "SHOW DATABASES LIKE 'nagiosna'")
    if [ "$DB_EXISTS" != "nagiosna" ]; then
        mysql -e "CREATE DATABASE nagiosna CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
        echo "Created database 'nagiosna'."
    else
        echo_c "Database 'nagiosna' already exists." "$ORANGE"
    fi

    USER_EXISTS=$(mysql -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'nagiosna' AND host = 'localhost')")
    if [ "$USER_EXISTS" -eq 0 ]; then
        mysql -e "CREATE USER 'nagiosna'@'localhost' IDENTIFIED BY '${NAGIOSNA_MYSQL_PASS_ESC}';"
        echo "Created database user 'nagiosna'@'localhost'."
    else
        echo_c "User 'nagiosna'@'localhost' already exists." "$ORANGE"
        mysql -e "ALTER USER 'nagiosna'@'localhost' IDENTIFIED BY '${NAGIOSNA_MYSQL_PASS_ESC}';"
        echo "Updated database user 'nagiosna'@'localhost' password."
    fi

    mysql -e "GRANT ALL PRIVILEGES ON nagiosna.* TO 'nagiosna'@'localhost';"
    mysql -e "GRANT PROCESS, SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER ON *.* TO 'nagiosna'@'localhost';"

    # Set root password last and flush privileges
    mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${ROOT_MYSQL_PASS_ESC}'; FLUSH PRIVILEGES;"
    echo "Set database root user password."
    export MYSQL_PWD="$ROOT_MYSQL_PASS"
}

artisan() {
    # Only generate an app key if one does not exist yet!
    if [ -z "$APP_KEY" ]; then
        cd "$proddir" && php artisan key:generate
    fi

    # Run migrations
    echo_c "Running database migrations..." "$BLUE"
    cd "$proddir" && php artisan migrate --force

    echo_c "Running database seeders..." "$BLUE"
    cd "$proddir" && php artisan db:seed
}

build_subcomponents() {
    cd "$INSTALL_PATH/subcomponents"

    # Install NFDump
    if command -v nfdump >/dev/null 2>&1; then
        echo_c "nfdump is already installed, skipping nfdump installation." "$ORANGE"
    else
        echo_c "Installing nfdump..." "$BLUE"
        tar xf nfdump-1.7.6.tar.gz
        cd nfdump-1.7.6
        ./autogen.sh
        ./configure --enable-sflow --enable-nsel
        make
        make install
        ldconfig
        cd ..
        rm -rf nfdump-1.7.6
    fi

    # Install rrdtool
    if command -v rrdtool >/dev/null 2>&1; then
        echo_c "RRDtool is already installed, skipping RRDtool installation." "$ORANGE"
    else
        echo_c "Installing rrdtool..." "$BLUE"
        tar xf rrdtool-1.7.2.tar.gz
        cd rrdtool-1.7.2
        mkdir -p /root/.python-eggs
        ./configure --prefix=/usr/local --disable-perl
        make
        make install
        ldconfig
        # Install python (and ignore temp file location perm warn)
        make site-python-install &>/dev/null
        cd ..
        rm -rf rrdtool-1.7.2
    fi

    # Install InfluxDB
    install_influxdb

    # Make sure librrd exists for el9
    if [ "$dist" == "el9" ]; then
        # found some systems where librrd is already installed, install script crashes here if we try to clobber.
        if [ ! -f /usr/lib64/librrd.so.8 ]; then
            ln -s /usr/local/lib/librrd.so.8 /usr/lib64/librrd.so.8
        fi
    fi

    # Install Chrome for Testing
    cd "$INSTALL_PATH/subcomponents/chrome"
    ./install.sh
    cd ..
}

backend() {
    # Setup the backend daemon for netflow processing
    add_to_groups "$apacheuser" nnacmd
    add_to_groups nna "$apacheuser"

    # Permissions for Laravel directories
    chown -R "$apacheuser":nnacmd "$proddir/storage" "$proddir/bootstrap/cache"
    chmod -R 0775 "$proddir/storage"
    chmod -R 0775 "$proddir/bootstrap/cache"
    cd "$proddir" && php artisan storage:link

    # Manually create laravel.log and cron.log
    mkdir -p "$proddir/storage/logs/updates"
    chown -R "$apacheuser":nnacmd "$proddir/storage/logs"
    chmod -R 2775 "$proddir/storage/logs"

    touch "$proddir/storage/logs/cron.log"
    chown nna:nnacmd "$proddir/storage/logs/cron.log"
    chmod 664 "$proddir/storage/logs/cron.log"

    mkdir -p "$backenddir/scripts"
    mkdir -p "$backenddir/var"
    cp -r "$INSTALL_PATH/scripts/"* "$backenddir/scripts/"

    chown -R nna:nnacmd "$backenddir"
    chmod -R 0775 "$backenddir"
    chown -R nna:nnacmd "$backenddir/var"
    # For security - this prevents nna from overwriting a file that it can run via `sudo`
    chown root:nnacmd "$backenddir/scripts"
    chmod 0755 "$backenddir/scripts"

    # Create backup directories for backup/restore scripts
    mkdir -p /store/backups/nagiosna
    chown -R nna:nnacmd /store
    chmod -R 0775 /store
}

copy_mibs() {
    mkdir -p $mibsdir
    cp "$INSTALL_PATH"/mibs/* $mibsdir
}

install_sudo() {
    # set sudoers for backend functions
    if [ -d /etc/sudoers.d/ ]; then
        cp "$INSTALL_PATH/nagiosna.sudoers" /etc/sudoers.d/nagiosna
    else
        cat "$INSTALL_PATH/nagiosna.sudoers" >> /etc/sudoers
    fi
}

selinux() {
    # Disable SELinux if it's enabled. This should be done on RHEL-based systems.
    if [ "$distro" != "Ubuntu" ] && [ "$distro" != "Debian" ]; then
        disable_selinux
        semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/nagiosna/storage(/.*)?"
        semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/nagiosna/bootstrap/cache(/.*)?"
        restorecon -Rv /var/www/html/nagiosna/storage
        restorecon -Rv /var/www/html/nagiosna/bootstrap/cache
        setsebool -P httpd_can_network_connect_db 1
    fi
}

apache() {
    echo_c "Creating Apache config file..." "$BLUE"

    cat "$INSTALL_PATH/nna.conf" > "$httpdconfdir/nna.conf"
    sed -i "s|<HTTPD>|$httpd|" "$httpdconfdir/nna.conf"

    if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
        # Activate module mod_rewrite and ssl
        a2enmod ssl
        a2enmod rewrite
        a2ensite default-ssl

        # Remove the default configuration
        a2dissite 000-default.conf
        a2ensite nna.conf
    fi

    sed -i "s|^\s*ServerName .*|    ServerName $IP_ADDRESS|" "${httpdconfdir}/nna.conf"

    echo_c "Setting up Apache..." "$BLUE"
    php_fpm_service=""
    if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
        # Find the installed PHP-FPM service by checking common versions
        for version in 8.4 8.3 8.2; do
            if systemctl list-units --full -all | grep -q "php${version}-fpm.service"; then
                php_fpm_service="php${version}-fpm"
                break
            fi
        done
    else
        php_fpm_service="php-fpm"
    fi

    echo_c "Configuring php.ini..." "$BLUE"
    PHP_MEMORY_LIMIT="2G"
    PHP_POST_MAX_SIZE="1200M"
    PHP_UPLOAD_MAX_FILESIZE="1G"

    if [[ "$distro" == "Ubuntu" || "$distro" == "Debian" ]]; then
        for ini in $phpini $phpcliini $phpfpmini; do
            set_php_ini "$ini" "memory_limit" "$PHP_MEMORY_LIMIT"
            set_php_ini "$ini" "post_max_size" "$PHP_POST_MAX_SIZE"
            set_php_ini "$ini" "upload_max_filesize" "$PHP_UPLOAD_MAX_FILESIZE"
        done
    else
        set_php_ini "$phpini" "memory_limit" "$PHP_MEMORY_LIMIT"
        set_php_ini "$phpini" "post_max_size" "$PHP_POST_MAX_SIZE"
        set_php_ini "$phpini" "upload_max_filesize" "$PHP_UPLOAD_MAX_FILESIZE"
    fi

    echo_c "Restarting $httpd..." "$BLUE"
    systemctl enable --now "$php_fpm_service"
    systemctl enable $httpd
    systemctl restart "$httpd"
}

daemons() {
    PHP_PATH="$(which php)"

    # Install Laravel Reverb
    echo_c "Installing Reverb..." "$BLUE"
    cd "$proddir" && php artisan reverb:install --no-interaction

    # Create cron job for Laravel scheduler
    echo_c "Setting up Laravel scheduler cron job..." "$BLUE"
    CRON_JOB="* * * * * nna cd $proddir && $PHP_PATH artisan schedule:run >> $proddir/storage/logs/cron.log 2>&1"
    echo "$CRON_JOB" > /etc/cron.d/nagiosna
    chmod 644 /etc/cron.d/nagiosna
    echo "Crontab for nna set to: $CRON_JOB"

    # Create an executable PHP binary for nna user
    EXE_PHP_PATH="/usr/local/bin/herd-php"
    rm -f "$EXE_PHP_PATH"
    cp "$PHP_PATH" "$EXE_PHP_PATH"
    chmod 755 "$EXE_PHP_PATH"
    chown root:nnacmd "$EXE_PHP_PATH"

    # Setup Supervisor for Laravel queues and Reverb
    echo_c "Setting up Supervisor..." "$BLUE"
    LOG_FILE_DIR="$proddir/storage/logs"

    mkdir -p $SUPERVISOR_SYSTEMD_SERVICE_DIR
    cat > $SUPERVISOR_SYSTEMD_SERVICE_OVERRIDE <<EOF
    [Unit]
    After=rc-local.service $mysqld.service
    Requires=$mysqld.service
EOF

    cat > $SUPERVISOR_CONFIG <<EOF
    [unix_http_server]
    file=/var/run/supervisor.sock    ; (path to the socket file)
    chmod=0770
    chown=root:nnacmd

    [supervisord]
    logfile=/var/log/supervisord.log ; (main log file)
    logfile_maxbytes=50MB            ; (num of main logfile bytes b4 rotation;default 50MB)
    logfile_backups=10               ; (num of main logfile rotation backups;default 10)
    loglevel=info                    ; (log level;default info; others: debug,warn,trace)
    nodaemon=false                   ; (start in foreground if true;default false)
    minfds=1024                      ; (min. avail startup file descriptors;default 1024)
    minprocs=200                     ; (min. avail process descriptors;default 200)
    pidfile=/var/run/supervisord.pid ; pidfile

    [rpcinterface:supervisor]
    supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

    [supervisorctl]
    serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL  for a unix socket

    [include]
    files = $SUPERVISOR_INCLUDES_DIR/*.ini
EOF

    cat > "$SUPERVISOR_INCLUDES_DIR/laravel-worker.ini" <<EOF
    [program:laravel-worker]
    process_name=%(program_name)s_%(process_num)02d
    command=$EXE_PHP_PATH $proddir/artisan queue:work --max-jobs=500
    autostart=true
    autorestart=true
    stopasgroup=true
    killasgroup=true
    user=nna
    numprocs=8
    redirect_stderr=true
    stdout_logfile=$LOG_FILE_DIR/worker.log
    stopwaitsecs=3600
EOF

    cat > "$SUPERVISOR_INCLUDES_DIR/laravel-reverb.ini" <<EOF
    [program:laravel-reverb]
    command=$EXE_PHP_PATH $proddir/artisan reverb:start
    autostart=true
    autorestart=true
    stopasgroup=true
    killasgroup=true
    user=nna
    redirect_stderr=true
    stdout_logfile=$LOG_FILE_DIR/reverb.log
EOF

    if ! pgrep -x "$SUPERVISOR_SERVICE" > /dev/null; then
        echo "Starting Supervisor..."
        systemctl enable $SUPERVISOR_SERVICE
        systemctl start $SUPERVISOR_SERVICE
    else
        echo_c "Supervisor is already running. Restarting..." "$ORANGE"
        supervisorctl stop all
        systemctl restart $SUPERVISOR_SERVICE
    fi

    echo "Reloading Supervisor config..."
    supervisorctl reread
    supervisorctl update

    echo "Starting Supervisor processes..."
    supervisorctl start all
    sleep 2
    status_output=$(supervisorctl status)

    if echo "$status_output" | grep -q "^laravel-reverb.*RUNNING"; then
        echo "laravel-reverb is running."
    else
        echo_c "ERROR: laravel-reverb is not running" "$RED"
        exit 1
    fi

    worker_count="$(echo "$status_output" | grep -E "^laravel-worker:laravel-worker_[0-9]+" | wc -l)"
    running_worker_count="$(echo "$status_output" | grep -E "^laravel-worker:laravel-worker_[0-9]+.*RUNNING" | wc -l)"
    if [ "$worker_count" -eq "$running_worker_count" ]; then
        echo "All $running_worker_count laravel-worker processes are running."
    else
        echo_c "ERROR: Some laravel-worker processes are not running" "$RED"
        echo "$status_output" | grep "^laravel-worker"
        exit 1
    fi

    echo "Supervisor setup completed!"

    echo_c "Setting up NagiosNA systemd services..." "$BLUE"

    sed -i "s|HTTPD|$httpd|;s|MYSQLD|$mysqld|;s|BACKENDDIR|$backenddir|" $INSTALL_PATH/nagiosna.service
    cp $INSTALL_PATH/nagiosna.service /etc/systemd/system/nagiosna.service

    sed -i "s|MYSQLD|$mysqld|" $INSTALL_PATH/nagiosna-update.service
    cp $INSTALL_PATH/nagiosna-update.service /etc/systemd/system/nagiosna-update.service

    systemctl daemon-reload
    systemctl enable nagiosna.service
}

configure_ldap() {
    # ldap configs, will change as needed
    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
        ldap_config="/etc/ldap/ldap.conf"
        ldap_dir="/etc/ldap"
        cacerts_dir="/etc/ldap/cacerts"
    else
        ldap_config="/etc/openldap/ldap.conf"
        ldap_dir="/etc/openldap"
        cacerts_dir="/etc/openldap/cacerts"
    fi

    mkdir -p "$cacerts_dir"
    mkdir -p "$ldap_dir/certs"
    chmod 775 "$ldap_dir/certs" "$cacerts_dir"
    chown -R "$apacheuser:nnacmd" "$ldap_dir/certs" "$cacerts_dir"
    if [ -f "$ldap_config" ]; then
        chown root:nnacmd "$ldap_config"
        chmod 664 "$ldap_config"
    fi

    if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
        mkdir -p /usr/local/share/ca-certificates
        chown "$apacheuser:nnacmd" /usr/local/share/ca-certificates
        chmod 775 /usr/local/share/ca-certificates
    fi
}

##############################
### START THE INSTALLATION ###
##############################

fullinstall() {
    # Parse command line
    while [ -n "$1" ]; do
        case "$1" in
            -h | --help )
                install_help
                exit 0
                ;;
            -f | --force )
                FORCE="True"
                ;;
            -n | --non-interactive )
                INTERACTIVE="False"
                ;;
            * )
                echo "Unknown option:  $1" >&2
                usage_install >&2
                exit 1
        esac
        shift
    done

    print_header "Nagios Network Analyzer"

    # Verify that Nagios Network Analyzer is not already installed
    if [ -f "$INSTALLED_FLAG" ]; then
        if [ "$FORCE" = "True" ]; then
            echo_c "Forcing re-install..." "$BLUE"

            # Backup the existing .env file
            if [ -f "$proddir/.env" ]; then
                echo "Backing up existing .env file..."
                cp "$proddir/.env" "$ENV_BACKUP"
            else
                echo_c "ERROR: Failed to find .env file in $proddir!" "$RED"
                exit 1
            fi

            echo "Removing existing installation..."
            rm -rf "$proddir"
            rm -rf "$backenddir"
            rm -f "$INSTALL_PATH"/installed*
            rm -f "$INSTALL_PATH/install.log"
            rm -f "$INSTALLED_FLAG"
        else
            echo_c "ERROR: It looks like Nagios Network Analyzer is already installed!" "$RED"
            echo_c "If you know what you're doing, you can run the installer with -f / --force to force the installation." "$RED"
            exit 1
        fi
    fi

    if [ "$INTERACTIVE" = "True" ]; then
        echo
        echo_c "Enter a password to use for the MySQL nagiosna user. It must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, and one digit. A random password will be chosen if one is not entered..." "$GREEN"
        prompt_for_password NAGIOSNA_MYSQL_PASS
        echo
        echo_c "Enter a password to use for the InfluxDB nagiosna user. It must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, and one digit. A random password will be chosen if one is not entered..." "$GREEN"
        prompt_for_password NAGIOSNA_INFLUX_PASS
        echo
    fi

    if ! path_is_ok; then
        echo "Your system \$PATH does not include /sbin and /usr/sbin."
        echo "Adding /sbin and /usr/sbin to \$PATH."
        PATH="$PATH:/usr/sbin:/sbin"
    fi

    run_steps create_users prereqs nagiosna install_sourceguardian firewall library_path db artisan backend build_subcomponents configure_influxdb copy_mibs install_sudo selinux apache daemons configure_ldap

    trap - 0

    touch "$INSTALLED_FLAG"

    unset ROOT_MYSQL_PASS
    unset ROOT_INFLUX_PASS
    unset NAGIOSNA_MYSQL_PASS
    unset NAGIOSNA_INFLUX_PASS

    # Clean up backup .env file if it exists
    if [ -f "$ENV_BACKUP" ]; then
        rm -f "$ENV_BACKUP"
    fi

    URL="http://$IP_ADDRESS/install"
    URL_LENGTH=${#URL}
    PADDING=$((45 - URL_LENGTH))

    echo
    echo_c "######################################################" "$CYAN"
    echo_c "#                                                    #" "$CYAN"
    echo_c "#   Nagios Network Analyzer Installation Complete!   #" "$CYAN"
    echo_c "#                                                    #" "$CYAN"
    echo_c "# -------------------------------------------------- #" "$CYAN"
    echo_c "#                                                    #" "$CYAN"
    echo_c "#   Complete the final setup steps by visiting:      #" "$CYAN"
    printf "${CYAN}#${NC}       ${BLUE}%s${NC}%*s${CYAN}#${NC}\n" "$URL" "$PADDING" ""
    echo_c "#                                                    #" "$CYAN"
    echo_c "######################################################" "$CYAN"
    echo
}

log_it install.log fullinstall "$@"