#!/bin/sh -e
SERVICE_NAME=dhclient
DHCLIENT_TEMPLATE="/usr/share/xs-config/cfg/etc/dhclient-hostname.conf.in"

# find the current gateway 
wan_iface=`route -n | awk '{if($4=="UG")print $8}'`

# grab the short hostname 
short_host=`hostname -s`

# ensure a default name
if [ $short_host != schoolserver ]; then
    short_host=schoolserver
fi

# append the passed domain name
domain=`cat /etc/sysconfig/xs_domain_name`
xs_full_name=$short_host.$domain

echo "changing FQDN to $xs_full_name" | tee -a /var/log/xs-setup.log
# change the config files
sed -i -e '/HOSTNAME=/d' /etc/sysconfig/network
echo "HOSTNAME=$xs_full_name " >> /etc/sysconfig/network
echo $xs_full_name  > /etc/hostname
hostname $xs_full_name

# clear any old config files
set +e
remove=`ls /etc/dhclient-*.conf`
for inf in $remove; do
    echo "removing $inf"
    rm -f $inf
done
set -e

if [ x$wan_iface != x ]; then
    # replace the hostname in the dhclient interface file 
    if [ -e $DHCLIENT_TEMPLATE ]; then
        sed -e s/@@BASEDNSNAME3@@/$short_host/ $DHCLIENT_TEMPLATE \
                > /etc/dhclient-$wan_iface.conf ;
    else
        echo "WARNING: missing $DHCLIENT_TEMPLATE!" | tee -a /var/log/xs-setup.log
    fi

    # kill the old lease file that has old hostname
    if [ -e /var/run/nm-dhclient-$wan_iface.conf ]; then
        rm /var/run/nm-dhclient-$wan_iface.conf
    fi
else
    echo "dhclient missing default gateway" | tee -a /var/log/xs-setup.log
fi

#donedns=`hostname -f` 
donedns=`hostname ` 
echo "dhclient - FQDN is $donedns" | tee -a /var/log/xs-setup.log

exit 0
