#!/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

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
