#!/bin/bash
#
# Guralp Configuration System
#   Copyright (c) 2007-2009 Guralp Systems Ltd. All rights reserved.
#
#   System ID or hostname.

# Load support functions
script_dir=$(dirname $0)
. $script_dir/functions.sh

do_read() {
	local hostname
	local hostmethod=none

	gcs_var d_hostname	"localhost"
	gcs_var d_domain_name	"local.net"

	# HOSTNAME
	# Gentoo location
	if [ -r $CONFDIR/hostname ]
	then
	    hostname=$(gcs_get_varf HOSTNAME $CONFDIR/hostname)
	    if [ -n "$hostname" ]
	    then
		hostmethod=conf
	    else
	    	hostname=$(sed -e 's/#.*//' -e 's/[ 	]*$//' -e '/^$/d' < \
			$CONFDIR/hostname)
		hostmethod=lwconf
	    fi

	# Old but still popular location
	elif [ -r $CFGROOT/etc/hostname ]
	then
	    hostname=$(cat $CFGROOT/etc/hostname)
	    hostmethod=etc

	# Old Guralp configDB
	elif [ -x /usr/bin/configdb ]
	then
	    hostname=$(configdb -r -g general.hostname)
	    if [ "X$hostname" != "XERROR" ]
	    then
		hostmethod=configdb
	    fi
	fi

	if [ "X$hostmethod" != "Xnone" ]
	then
	    gcs_var o_hostname "$hostname"
	    gcs_var o_hostmethod "$hostmethod"
	fi

	# DOMAINNAME
	if [ -r $CFGROOT/etc/resolv.conf ]
	then
	    o_domain_name=$(sed -n -e '/^domain /s/.* //p' \
					$CFGROOT/etc/resolv.conf )
	    [ -n "$o_domain_name" ] && gcs_var o_domain_name "$o_domain_name"
	fi

}

do_check() {
	gcs_read_vars

	case "X$new_hostmethod" in
	Xconfigdb|Xetc|Xlwconf|Xconf|Xnone|X)
	    ;;
	*)
	    gcs_err msg "Unknown save method \"$new_hostmethod\""
	    ;;
	esac
}

do_write() {
	local err

	do_check
	if (( gcs_errors > 0 ))
	then
	    return
	fi

	case "X$new_hostmethod" in
	Xconfigdb)
		if [ -x /usr/bin/configdb ]
		then
		    if err=$(configdb -s general.hostname=$new_hostname)
		    then
			: Okay
		    else
			gcs_err msg "$err"
		    fi
		else
		    gcs_err msg "No configdb command to save setting ?"
		fi
		;;
	Xetc)
		if [ -w $CFGROOT/etc/hostname ]
		then
		    echo "$new_hostname" > $CFGROOT/etc/hostname
		else
		    gcs_err msg "Unable to write $CFGROOT/etc/hostname"
		fi
		;;
	Xconf)
		gcs_set_varf HOSTNAME $CONFDIR/hostname $new_hostname
		;;
	Xlwconf|Xnone|X)
		echo $new_hostname > $CONFDIR/hostname
		;;
	esac

	if (( gcs_errors > 0 ))
	then
	    return
	fi

	suexec hostname $new_hostname
}

do_bar() {
	echo "hostname	Hostname"
}

case "X$1" in
X--check)	do_check	;;
X--write)	do_write	;;
X--read)	do_read		;;
X--navbar)	do_bar		;;
*)		exit 1		;;
esac

gcs_cleanup
exit 0
