#!/bin/bash -e

. ./fusion-sys.cfg

# Was previous step completed?
if [ ! -f installed.subsystem ]; then
    echo "Subsystem was not installed - run previous script" >&2
    exit 1
fi

# Is security already configured?
if [ -f installed.security ]; then
    echo "Security already initialized - skipping..."
    exit 0
fi

# Add configuration to sudoers file
# --------------

# Remove old sudoers entries
grep -v NAGIOSXI /etc/sudoers > /etc/sudoers.new
mv -f /etc/sudoers.new /etc/sudoers

# Remove TTY requirement
sed -i 's/^Defaults    requiretty/#Defaults    requiretty/g' /etc/sudoers

# Add new sudoers entries
if [ -d "/etc/sudoers.d" ]; then
    cp inc/sudoers /etc/sudoers.d/nagiosfusion
    chmod 440 /etc/sudoers.d/nagiosfusion
else
    cat inc/sudoers >> /etc/sudoers
fi

# Set permissions
chmod 440 /etc/sudoers

# Replace apache user with www-data for Ubuntu installs
if [ "$distro" == "Ubuntu" ] || [ "$distro" == "Debian" ]; then
	sed -i 's/=apache/=www-data/' /etc/sudoers
    sed -i 's/NAGIOSFUSIONWEB=apache/NAGIOSFUSIONWEB=www-data/' /etc/sudoers.d/nagiosfusion
fi

# Generate key for encrypting sensitive data
# --------------

cat /dev/urandom | tr -dc "A-Za-z0-9" | head -c 8192 > $proddir/var/key
chown root:nagios $proddir/var/key
chmod 440 $proddir/var/key

echo "Security configured OK"
touch installed.general