#!/bin/bash -e


# get current working directory
BASEDIR=$(dirname $(readlink -f $0))


# Create setup environment
pushd ./setup/
. ./init.sh
. ./fusion-sys.cfg
. ./functions.sh
popd


# Install log
log="$BASEDIR/install.log"


# Initialize install.log
cat >> "$log" <<-EOF
Nagios Fusion Installation Log
==============================
DATE: $(date)

DISTRO INFO:
$distro
$version
$architecture

EOF


# Installation is interactive by default
export INTERACTIVE="True"


# INSTALL_PATH is current dir for use in making install dir independent
export INSTALL_PATH=`pwd`


# Add /usr/sbin and /sbin to PATH if it doesn't exist
if ! path_is_ok; then

    {
    echo "Your system \$PATH does not include /sbin and /usr/sbin."
    echo "Adding /sbin and /usr/sbin to \$PATH."
    } | tee -a "$log"

    PATH="$PATH:/usr/sbin:/sbin"
fi


# ====================
# Script Main
# --------------------
while [ -n "$1" ]; do
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
        -v | --version)
            sed -n '/full/ s/.*=//p' "${0%/*}/fusion/var/fusionversion"
            exit 0
            ;;
        -n | --non-interactive)
            export INTERACTIVE="False"
            ;;
        -p | --mysql-password)
            mysqlpass="$2"
            setvar mysqlpass "$2"
            shift
            ;;
        *)
            echo "Unknown option:  $1" >&2
            usage >&2
            exit 1
    esac
    shift
done


# CentOS and RHEL support for now
if [ "$INTERACTIVE" = "True" ]; then
    {
    fmt -s -w $(tput cols) <<-EOF

=======================
Nagios Fusion Installer
=======================

This script will do a complete install of Nagios Fusion by executing all necessary sub-scripts.

IMPORTANT: This script should only be used on a 'clean' install of CentOS, RHEL, Ubuntu or Debian. To create such a clean install you should have selected ONLY the 'Base' package in the OS installer.

EOF
    } | tee -a "$log"

    read -p "Do you want to continue? [Y/n] " res

    {
    case "$res" in
        Y | y | "")
            echo "Proceeding with installation..."
            ;;
        *)
            echo "Installation cancelled"
            exit 0
    esac
    } | tee -a "$log"
fi


# Database pre-initialization
{
echo "Checking MySQL credentials..."

# Check Mysql root password if MySQL is already installed and running...
if service $mysqld status &>/dev/null; then
    # Test for null MySQL root password
    if mysqlshow -u root &>/dev/null; then
        echo "After installation your MySQL root password will be set to 'fusion' (without quotes)."
    elif mysqlshow -u root -p"$mysqlpass" &>/dev/null; then
        echo "Stored MySQL password validated."
    else
        for i in 1 2 3; do
            if [ "$INTERACTIVE" = "True" ]; then
                echo "Enter the MySQL root password to continue..."
                read -p "MySQL Root Password: " pass
            fi

            # Test the password
            if mysqlshow -u root -p"$pass" &>/dev/null; then
                echo "Password validated."
                mysqlpass="$pass"

                # Update fusion-sys.cfg with MySQL password for later use
                if ! setvar mysqlpass "$mysqlpass"; then
                    echo "ERROR: Failed to update fusion-sys.cfg with MySQL password - exiting." >&2
                    exit 1
                fi

                break
            else
                echo "Password failed." >&2
                [ $i -eq 3 ] && exit 1
            fi
        done
    fi
else
    echo "MySQL not yet installed - that's okay."
fi
} | tee -a "$log"

{
if [ ! -f "$proddir/var/fusionversion" ]; then
    echo "THIS IS A NEW INSTALL!"
else
    echo "THIS IS AN UPGRADE!"
    echo
    echo "OLD VERSION:"
    grep -v "#" "$proddir/var/fusionversion"
fi
echo
echo "INSTALLING:"
grep -v "#" fusion/var/fusionversion
echo
} | tee -a "$log"


# ======================
# Run actual setup stubs
# ----------------------
pushd ./setup/
run_sub ./00-repos.sh noupdate
run_sub ./01-prereqs.sh
run_sub ./02-usergroups.sh
run_sub ./03-database.sh
run_sub ./04-general.sh
run_sub ./05-basedir.sh
run_sub ./06-sourceguardian.sh
run_sub ./07-subsystem.sh
run_sub ./08-security.sh
run_sub ./09-finish.sh
# PDF Creation not yet supported, putting this here for when that happens
#run_sub ./10-wkhtmltopdf.sh
run_sub ./11-ad-ldap-integration.sh
popd

{

# Restart services
echo "Restarting apache.."
$proddir/scripts/manage_services.sh restart $httpd
echo "Restarting mysql.."
$proddir/scripts/manage_services.sh restart mysqld
echo "Restarting crond.."
$proddir/scripts/manage_services.sh restart $crond

} | tee -a "$log"


echo
echo "Install complete!"

# Get IP address
ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet[^6]/{print substr($2,0)}' | sed 's|/.*||')
if [ "$ip" == "" ]; then
    ip=$(ip addr | grep global | grep -m 1 'inet' | awk '/inet6/{print substr($2,0)}' | sed 's|/.*||')
    if [ "$ip" == "" ];then
        ip="<HOSTNAME>"
    else
        ip="[$ip]"
    fi
fi

cat <<-EOF

    Nagios Fusion Installation Complete!
    ------------------------------------

    You can access the Nagios Fusion web interface by visiting:
        http://${ip}/nagiosfusion/

EOF