#!/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 hostname/domain setting tool for Zenwalk Linux

version='1.0'  	# - 13/05/2007 Birth
# Ported to yad (X-only, no gettext) by Claude.

if ! command -v yad >/dev/null 2>&1; then
	echo "yad is required but was not found in PATH." >&2
	exit 1
fi

if [ ! "$DISPLAY" ]; then
	echo "This program requires a running X session." >&2
	exit 1
fi

export PATH="${PATH}:/usr/sbin:/sbin"

if [ "$(id -u)" != "0" ]; then
	yad --center --title "Root only" --text "You need to be root to run $(basename $0)" --button="OK:0"
	exit
fi

# 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 )"

result=$(yad --center --width=460 \
	--title "Host and domain" \
	--text "Enter Hostname and Domain names:\n(these parameters will be applied upon reboot)" \
	--form --columns=1 \
	--field="Hostname" "$currenthostname" \
	--field="Domain" "$currentdomain" \
	--button="OK:0")

newhostname="$(echo "$result" | cut -d'|' -f1)"
newdomain="$(echo "$result" | cut -d'|' -f2)"

[ ! "$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
