#!/bin/sh
#
#
# chkconfig: - 49 88
# description: Set hostname

WITHOUT_RC_COMPAT=1


# Source function library.
. /etc/init.d/functions

# libshell
. shell-config
. shell-ip-address

retVAL=0

get_hostname()
{
    /sbin/ip -o -f inet address | grep -v 'lo[[:space:]]*inet' | sed 's/.*inet \(.*\)\/.*/\1/' |
      while read ipaddr; do
          valid_ipv4 "$ipaddr" || continue
          hostinfo -n "$ipaddr" || continue
          break # catch first successful name resolution
      done
}

start()
{

    local CFG="/etc/sysconfig/network"
    local hostname iplist

        # Suppose that all network interfaces already configured.
        # Try to fetch host name information using `hostinfo'.
        #
        # Suppose DNS resolver already configured.
        #
        # Should be executed before /etc/init.d/avahi-daemon start, to ecape delays.
        #

        hostname="$(get_hostname)"
        test -z "$hostname" && hostname="localhost.localdomain"
        shell_config_set "$CFG" HOSTNAME "$hostname"
        shell_config_set "$CFG" DOMAINNAME "$(echo $hostname | sed -e 's/[[:alnum:]]*\.*//')"

        # Read in config data
        SourceIfNotEmpty /etc/sysconfig/network

        if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then
            HOSTNAME="localhost.localdomain"
        fi

        # Set the hostname
        action "Setting hostname $HOSTNAME:" hostname "$HOSTNAME"
}


# See how we were called.
case "$1" in
    start)
    start
    ;;
    stop|condstop|status)
    ;;
    restart|reload|condrestart|condreload)
    ;;
    *) 
    msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
    RETVAL=1
esac

exit $RETVAL
