#!/bin/bash

# This script updates system configuration state based on the values
# of configuration install parameters.

# Set the defaults (i.e., disable sshd, delete the root password, and set
# root's shell to /bin/appliancesh).  Although it would be ideal to bake
# these settings in to cloudvmbase, it is not too late to make these settings
# here, because this code runs during the firstboot process which occurs
# during boot before ssh or console login is possible.  I'm reluctant to
# alter cloudvmbase now (due to fear of breaking all its consumers), but
# it should be done eventually.
echo "disabling ssh"

service sshd stop 2>&1 | tee -a $cloudvmlog

if ! /usr/bin/passwd -d root; then
    echo "ERROR: Unable to delete root password"
fi
echo "setting shell to appliancesh"
if ! /usr/bin/chsh -s /bin/appliancesh root; then
    echo "ERROR: Unable to set root shell"
fi

install_param=/bin/install-parameter
rootpasswd=`$install_param appliance.root.passwd .DEFAULT`
if [ "$rootpasswd" != ".DEFAULT" ] && [ "x$rootpasswd" != "x" ]; then
    echo "Setting root and grub passwords."
    echo "$rootpasswd" | /bin/set-root-passwd
    if [ $? -ne 0 ] ; then
        echo "ERROR: Unable to set root/grub passwords."
    fi
fi

echo "shell" `$install_param appliance.root.shell .DEFAULT`
echo "shell2" `$install_param appliance.root.shell2 .DEFAULT`

rootshell=`$install_param appliance.root.shell2 .DEFAULT`
if [ "$rootshell" = ".DEFAULT" ]; then
    rootshell=`$install_param appliance.root.shell .DEFAULT`
fi
if [ "$rootshell" != ".DEFAULT" ] && [ -e "$rootshell" ] && \
   [ "x$rootshell"  != "x" ]; then
    echo "Setting root shell to '$rootshell'."
    if ! /usr/bin/chsh -s "$rootshell" root; then
        echo "ERROR: Unable to set root shell to '$rootshell'."
    fi
fi

echo "   Allow ssh connections from all hosts"
echo "sshd: ALL : ALLOW" >> /etc/hosts.allow

sshenabled=`$install_param appliance.ssh.enabled .DEFAULT`
sshenabled=`echo "$sshenabled" | awk '{ print tolower($0) }'`
if [ "$sshenabled" = "true" ]; then
    echo "Enabling sshd."
    if ! /sbin/chkconfig sshd on; then
        echo "ERROR: Unable to enable sshd."
    fi
    # Starting it for now to get sshd running ASAP (for debugging).
    service sshd start 2>&1 | tee -a $cloudvmlog
else
    echo "Disabling sshd."
    if ! /sbin/chkconfig sshd off; then
        echo "ERROR: Unable to disable sshd"
    fi
    service sshd stop 2>&1 | tee -a $cloudvmlog
fi
