#!/bin/bash

# Copyright Jean-Philippe Guillemin <jp.guillemin@free.fr>. This program is free software;
# you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm

# Hostconfig is a simple GTK/NCURSES hostname/domain setting tool for Zenwalk Linux


version='1.0'  	# - 13/05/2007 Birth


# Take a look at "Xdialog" and use it instead of "dialog" in case X is running
if [[ "$DISPLAY" && "$(which Xdialog 2>&1 | grep -v "which: no")" ]]; then
	dialog="Xdialog --wrap --left --icon hostconfig"
	shortttl='3000'
	longttl='8000'
	xflag='yes'
else
	dialog="dialog"
	shortttl=''
	longttl=''
	xflag='no'
fi

# Gettext internationalization
export TEXTDOMAIN="hostconfig"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

# Path needs to be extended in case you're only half a root :)
export PATH="${PATH}:/usr/sbin:/sbin"

# Some globals

resolv='/etc/resolv.conf'
hosts='/etc/hosts'
hostnamefile='/etc/HOSTNAME'


# Save some config files
cat $hosts > $hosts.old
cat $hostnamefile > $hostnamefile.old

###############################################
# Set Hostname and Domain name

currenthostname="$(cut -d. -f1 -s $hostnamefile )"
currentdomain="$(cut -d. -f2- -s $hostnamefile )"

if [ ! "$dialog" = "dialog" ]; then
newvalue="$($dialog --stdout --title "$(eval_gettext 'Host and domain')" --no-cancel --2inputsbox "$(eval_gettext 'Enter Hostname and Domain names :')\n($(eval_gettext 'these parameters will be applied upon reboot'))  " 16 70 \
"$(eval_gettext 'Hostname')" "$currenthostname" \
"$(eval_gettext 'Domain')" "$currentdomain")"
  newhostname="$(echo $newvalue | cut -d / -f 1 )"
  newdomain="$(echo $newvalue | cut -d / -f 2 )"
else
  newhostname="$($dialog --stdout --title "$(eval_gettext 'Hostname')" --no-cancel --inputbox "$(eval_gettext 'Enter the Hostname') :" 11 75 "$currenthostname")"
  newdomain="$($dialog --stdout --title "$(eval_gettext 'Domain')" --no-cancel --inputbox "$(eval_gettext 'Enter the Domain name') :" 11 75 "$currentdomain")"
fi

[ ! "$newhostname" ] && exit

# save parameters
# hosts file
noloopback="$(grep -v "^127.0.0.1" $hosts)"
echo "$noloopback" > $hosts
echo "127.0.0.1		localhost" >> $hosts
if [ "$newdomain" ]; then
  echo "127.0.0.1		$newhostname.$newdomain $newhostname" >> $hosts
else
  echo "127.0.0.1		$newhostname" >> $hosts
fi

# HOSTNAME file
if [ "$newdomain" ]; then
  echo "$newhostname.$newdomain" > $hostnamefile
else
  echo "$newhostname" > $hostnamefile
fi

# resolv.conf file
if [ "$newdomain" ]; then
  nodomain="$(sed -e '/^search[ \t]*.*$/d' -e '/^domain[ \t]*.*$/d' $resolv)"
  echo "search $newdomain" > $resolv
  echo "domain $newdomain" >> $resolv
  echo "$nodomain" >> $resolv
fi


# end
