#!/bin/bash
#
# A install script for Micetro on BDDS
#


# If neither micetro.uuid, or updater's preference file (for older micetro versions) exist
# then we assume it's a fresh installation of an MDDS that's never been connected to Micetro.
# Otherwise, this is probably being invoked by the MDDS upgrade procedure, when psm is likely 
# unreachable, and in case of xHA, the replicated folder is mounted but more or less empty 
CLEAN_INSTALL=true
if [ -s "/var/mmsuite/micetro.uuid" ] || [ -s "/var/mmsuite/updater/preferences.cfg" ]; then
    echo "Detected existing installation"
    CLEAN_INSTALL=false
else
    echo "Detected fresh installation"
fi


# Disable and mask CommandServer to prevent start on reboot.
echo "Disabling and masking CommandServer"
/usr/local/bluecat/PsmClient node set command-server-enable=0
systemctl mask cs


echo "Adding firewall rules for Micetro services"
MANAGEMENT_INTERFACE=`grep -oP '(?<=<activeManagementInterface>).*?(?=</activeManagementInterface>)' /etc/bcn/psm.xml`
if [ "$MANAGEMENT_INTERFACE" != "eth2" ]; then
    # It should be either eth0 or eth2. If it is not eth2 assume eth0
    MANAGEMENT_INTERFACE="eth0"
fi
echo "Management interface: $MANAGEMENT_INTERFACE"
sed -e "s,__MANAGEMENT_INTERFACE__,$MANAGEMENT_INTERFACE,g" mm-rules.iptables.in > mm-rules.iptables
/usr/local/bluecat/custom_fw_rules --import-rules ./mm-rules.iptables

# Ensure that named-checkconf can call chroot to validate the config in the chroot jail.
echo "Ensuring named-checkconf works in chroot"
for path in "/usr/local/sbin/named-checkconf" "/usr/local/bin/named-checkconf"; do
    if [ -e "$path" ]; then
        chown named "$path"
        chmod +s "$path"
        setcap cap_sys_chroot+ep "$path"
        break
    fi
done

echo "Ensuring correct ownership in jail"
chown -R named:named /replicated/jail/named/usr
chown -R named:named /replicated/jail/named/var

# Create fresh dhcpd.conf and named.conf, if needed
./create_dhcpd_conf # no-op if dhcpd.conf already exists
./create_named_conf # only ensures rndc.conf access if named.conf already exists


# Copy additional files needed.
echo "Copying source files"
cp -r source/* /

# Make sure we have to correct privileges on the files.
chmod 755 /usr/local/mm/*
chmod 644 /usr/local/mm/*.conf


if [ "$CLEAN_INSTALL" == true ]; then
    # If this is a clean install then by default we should enable SNMP.
    echo "Enabling snmp"
    /usr/local/bluecat/PsmClient -f ./snmp_conf.json
    /usr/local/bluecat/PsmClient node set snmp-enable=1
fi
echo "install complete"
