#!/bin/sh
# console-config/src/sbin-scripts/hostname-setup
# 
#  Copyright: ©2014, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Allow setting of the system hostname.
#

HOSTNAME_CONFIG_FILE="/etc/conf.d/hostname.local"
MAX_LENGTH="60"



# do_set_hostname()
#  Tries to set the given hostname. Checks for a couple of bad conditions
#  and then hands off to the hostname utility. If that works, updates the
#  config file. In any case, exits the program.
do_set_hostname() {
    NEW_NAME="$1"

    if [ "${#NEW_NAME}" -eq 0 ]
    then
        echo "$0: cannot set an empty hostname." >& 2
        exit 1
    fi

    if [ "${#NEW_NAME}" -gt "${MAX_LENGTH}" ]
    then
        echo "$0: host name too long (max ${MAX_LENGTH} bytes)." >& 2
        exit 1
    fi

    TR_NAME="`echo -n \"${NEW_NAME}\" | tr ' .?*$	
' '________'`"
    if [ "${NEW_NAME}" != "${TR_NAME}" ]
    then
        echo "$0: host name contains illegal characters." >& 2
        echo "$0: note qualified domain names are not allowed here." >& 2
        exit 1
    fi

    hostname "${NEW_NAME}" || exit 1

    cat > "${HOSTNAME_CONFIG_FILE}.new" <<EOF
# /etc/conf.d/hostname
#  This file should consist of a single non-comment token, which is the
#  hostname to set.
#
#  This file was created on `isodate -me` by $0.
#

${NEW_NAME}
EOF
    [ $? -eq 0 ] || exit 1
    mv "${HOSTNAME_CONFIG_FILE}.new" "${HOSTNAME_CONFIG_FILE}"
    [ $? -eq 0 ] || exit 1
    echo "Hostname updated. Note a reboot may be required for all services"
    echo "to switch to the new name."
    exit 0
}



#
# Commandline processing
#

if [ $# -eq 1 ]
then
    # one parameter — assume hostname to set
    do_set_hostname "${HOSTNAME_CONFIG_FILE}"
fi

if [ $# -ne 0 ]
then
    echo "$0: expecting either 0 or 1 parameter (hostname to set)." >& 2
    exit 1
fi



# Show selection dialog. Result will be on stderr.
DIALOG_RESULTFILE="`mktemp`"
trap "rm -f \"${DIALOG_RESULTFILE}\"" EXIT

dialog --title "Hostname" \
    --trim --max-input "${MAX_LENGTH}" \
    --inputbox "Enter new hostname (no dots):" \
	8 68 "`hostname`" \
	2> "${DIALOG_RESULTFILE}"

if [ $? -ne 0 ]
then
	clear
	echo "Cancelled."
	rm -f "${DIALOG_RESULTFILE}"
	exit 1
fi

clear
do_set_hostname "`cat "${DIALOG_RESULTFILE}"`"


# vim: ts=4:sw=4:expandtab
