#!/bin/bash

#
# $Id: add_xterm,v 1.23 1998/01/12 12:32:06 root Exp root $
#
# Create links, files and file entries to enable a machine as an Xterminal
# client of this server.
#
## 
## Copyright (c) 1997, 1998  John Little (gaijin@pobox.com)
## 
## Permission is hereby granted, free of charge, to any person obtaining a
## copy of this software and associated documentation files (the "Software"),
## to deal in the Software without restriction, including without limitation
## the rights to use, copy, modify, merge, publish, distribute, sublicense,
## and/or sell copies of the Software, and to permit persons to whom the
## Software is furnished to do so, subject to the following conditions:
## 
## The above copyright notice and this permission notice shall be included
## in all copies or substantial portions of the Software.
## 
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
## THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
## OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
## ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
## OTHER DEALINGS IN THE SOFTWARE.
##
#

set -h;
##set -x;							## Debug flag.

PATH=/bin:/usr/bin:/usr/sbin:/sbin;
PROGNAME=${0};
NAME=`basename ${PROGNAME}`;
export PATH NAME;

AWK=gawk;
TFTP_DIR=/tftpboot;
XDM_DIR=/usr/X11/lib/X11/xdm;

echo "Initializing...";
#include
. /usr/local/bin/._functions.sh;				## Function lib.
. /usr/local/bin/._hosts_update.sh;				## Function lib.

#
################################################################################
#
# Most things below this line should probably be left as they are.
#
HOSTS=/etc/hosts;
ETHERS=/etc/ethers;
TFTP_KERN=SPARClinux;
TFTP_ROOT=SLXT_root;
SIP_VAR=" ##SERVER_IP##";
X_SERVERS=${XDM_DIR}/Xservers;
XDM_CONFIG=${XDM_DIR}/xdm-config;
XSU_TEMPL=${XDM_DIR}/Xsetup.Template;

FILE_LIST="${HOSTS} ${ETHERS} ${X_SERVERS}";
DIR_LIST="${TFTP_DIR} ${XDM_DIR} ${TFTP_DIR}/${TFTP_ROOT}";

#
# Get a hostname from the user. Munge the resulting input to make it
# more digestable (convert whitespace to underscores and upper-case
# to lower).
#
Get_Hostname(){
	cat > /dev/tty <<- EO_GETHST

        Please input a hostname for your new SPARC-Xterminal 
        (Note: You do NOT need to add the domain name: ${DNS_DOM}).

	EO_GETHST

	while [ "${XTERM_NAME:-NoTSeT}" = "NoTSeT" ];	do
		echo -n "	Hostname: "		>/dev/tty;
		read XTERM_NAME				</dev/tty;
	done
	XTERM_NAME=`echo "${XTERM_NAME}" | tr '[:blank:]' '_' | tr A-Z a-z`;
}

Get_Dom(){
	DNS_DOM=`dnsdomainname`;
	[ ${?} -ne 0 ] && Fatal "Unable to determine domainname.";
	if [ -z "${DNS_DOM}" ];	then
		cat > /dev/tty <<- EO_DOMERR

         	The DNS domainname for this system is blank. If
        	this is incorrect you should abort and set up your
        	/etc/hosts file correctly.

        	If you are not using a DNS domainname, select continue
        	and the simple, non-qualified hostname will be used.

		EO_DOMERR

		YorN "Continue?";
		[ ${?} -ne 0 ] && exit 0;
		DNS_DOM="NULL";
	fi
	return 0;
}

#
# Get server IP and hostname for later use.
#
ID_Server(){
	SERVER=`uname -n`;
	[ ${?} -ne 0 -o -z "${SERVER}" ] && Error "\"uname\" failed.";

	if [ -z "${SERVER}" ];	then
		[ -z "${HOSTNAME}" ] && \
			Fatal "Cannot get hostname for this machine";
		SERVER=`echo ${HOSTNAME} | cut -d. -f1`;
		[ ${?} -ne 0 -o -z "${SERVER}" ] && \
			Fatal "Cannot determine hostname for this system";
	fi

	HOST_HITS=0; DOMN_HITS=0;
	Grok_HName "${HOSTS}" "${SERVER}";
	if [ ${HOST_HITS} -gt 1 ];	then
		GH_Error;
		Fatal "Fix ${HOSTS} and restart...";
	elif [ ${HOST_HITS} -eq 1 ];	then
		eval `echo "${HOST_HIT_1}" | ${AWK} '
			{	split($1, SEG_A, ".");
				printf("SEG_IP=\"%d.%d.%d.\";\n", 
					SEG_A[1], SEG_A[2], SEG_A[3]);
				printf("SERVER_IP=\"%s\";\n", $1);
			}'`;
		[ ${?} -ne 0 -o -z "${SEG_IP}" \
			-o -z "${SERVER_IP}" ] && Fatal \
			"Error while getting segment IP from ${HOST_HIT_1}";
	else
		Fatal "Could not get ${SERVER} address from ${HOSTS}";
	fi
	return 0;
}

#
# Get an IP address from the user. This needs to be in the same segment
# as the server (the machine this script is running on) and for the time
# being we will assume a class-C network (most people seem to use class-C
# address format, even when their address is in an A or B range).
#
Get_IP(){
	[ -z "${SEG_IP}" ] && Fatal "Segment IP address has not been  set.";
	cat >/dev/tty <<- EO_IP

        Please input an IP address for your SPARC-Xterminal between
        "1" and "254".

	EO_IP
	while [ "${IP_SUFF:-NoTSeT}" = "NoTSeT" ];	do
		echo -en "\t${SEG_IP}";
		read IP_SUFF				< /dev/tty;
		case ${IP_SUFF} in
			[0-9]|[0-9][0-9]|[0-9][0-9][0-9])
				if [ ${IP_SUFF} -lt 1 -o ${IP_SUFF} -gt 254 ]
				then
					echo -e "\n\a\t1 ~ 254 only, please.\n" >&2;
					IP_SUFF=;
				fi
				XTERM_IP="${SEG_IP}${IP_SUFF}";
				Totty "";;

			*)	echo -e "\n\a\tNumeric input only, please.\n" >&2;
				IP_SUFF=;;
		esac
	done
	IP_IN_USE=`cat ${HOSTS} | egrep -v "^#" | egrep "^${XTERM_IP}"`;
	case ${?} in
		0)	Error "IP already in use:-";
			echo "${IP_IN_USE}"		>/dev/tty;
			XTERM_IP=; IP_SUFF=;
			Restart ${PROGNAME};
			exit 0;;

		1)	Totty "Using: ${XTERM_IP} ${XTERM_NAME}";;

		*)	Fatal "IP check failed.";
	esac
}

#
# Warn of gross error in hosts file.
#
GH_Error(){

	cat >/dev/tty 2>&1 <<- EO_GH_ERROR

        There is more than one line in the ${HOSTS} file with
        an entry for the hostname you have just selected ("${XTERM_NAME}").
        Hostnames need to be unique within a domain. 

	EO_GH_ERROR

	while [ ${HOST_HITS} -gt 0 ];	do
		eval `echo "" | ${AWK} '
		BEGIN {	HOST_HITS	= "'"${HOST_HITS}"'" + 0;
		}
		{	printf("echo \"${HOST_HIT_%d}\";\n", HOST_HITS);
			printf("HOST_HITS=%d;\n", --HOST_HITS);
		}'`;
	done
}

#
# Warn the user of a hostname/domainname clash.
#
Dom_Warn(){

	cat >/dev/tty 2>&1 <<- EO_DOMWN

        The ${HOSTS} file contains several lines which have the hostname
        you have just selected ("${XTERM_NAME}") as part of an existing
        domain name. While this is not a fatal error, it is bad practice
        and you probably should restart and select another hostname.

	EO_DOMWN

	while [ ${DOMN_HITS} -gt 0 ];	do
		eval `echo "" | ${AWK} '
		BEGIN {	DOMN_HITS	= "'"${DOMN_HITS}"'" + 0;
		}
		{	printf("echo \"${DOMN_HIT_%d}\";\n", DOMN_HITS);
			printf("DOMN_HITS=%d;\n", --DOMN_HITS);
		}'`;
	done
}

#
# Check for occurences of selected hostname in the existing entries
# in the hosts file.
#
Check_Hostname(){
	HOST_HITS=0; DOMN_HITS=0;
	Grok_HName "${HOSTS}" "${XTERM_NAME}";
	if [ ${DOMN_HITS} -gt 0 ];	then
		Error "Domain-name/hostname conflict:-";
		Dom_Warn;
		Restart ${PROGNAME};
		YorN "Continue?";
		[ ${?} -ne 0 ] && exit 0;
	fi
	if [ ${HOST_HITS} -gt 1 ];	then
		GH_Error;
		Fatal "Fix ${HOSTS} and restart...";
	elif [ ${HOST_HITS} -eq 1 ];	then
		Totty "Hostname exists in ${HOSTS}:-";
		echo -e "\t${HOST_HIT_1}"			>/dev/tty;
		XTERM_IP=`echo "${HOST_HIT_1}" | ${AWK} '{print $1}'`;
		[ ${?} -ne 0 -o -z "${XTERM_IP}" ] && \
			Fatal "Could note get IP address from ${HOST_HIT_1}.";
	else
		#
		# No existing hosts entry. Create one.
		#
		Get_IP;
		[ ${?} -ne 0 -o -z "${XTERM_IP}" ] && \
			Fatal "Failed to get IP address for \"${XTERM_NAME}\".";
		Update_Net_File ${HOSTS} \
				"${XTERM_IP}" "${XTERM_NAME}" "${DNS_DOM}";
		[ ${?} -ne 0 ] && \
			Fatal "Update failed: ${HOSTS}. Check Back-up.";
	fi

	#
	# Get Hex version of IP.
	#
	HEX_IP=; IP_ToHex "${XTERM_IP}";
	[ ${?} -ne 0 -o -z "${HEX_IP}" ] && \
		Fatal "Hex conversion of IP address failed.";
}

Check_EtherAdd(){
	eval `echo "${1}" | tr a-z A-Z | ${AWK} -F: '
	BEGIN {	BELL	= "\007";
		F_CNT	= 6 + 0;
		C_CNT	= 2 + 0;
		ERR_CNT	= 0 + 0;
	}
	function abort(info){
		printf("%c\n\tBad HEX-word: %s\t- See example above.\n\n",
						BELL, info) | "cat - >&2";
		ERR_CNT++;
		exit;
	}
	function chk_words(word){
		L_WORD	= word;
		W_LEN	= length(L_WORD);
		if (W_LEN != C_CNT) {
			abort(L_WORD);
		}
		for (x=1; x<=C_CNT; x++){
			CHAR	= substr(L_WORD, x, 1);
			if (CHAR !~ /[0123456789]|[ABCDEF]/) {
				abort(L_WORD);
			}
		}
		return 0;
	}
			
	NF != F_CNT { abort($0); }
	{
		for (i=1; i<=F_CNT; i++) {
			F_LEN = length($i);
			if (F_LEN < 1 || F_LEN > 2) {
				abort($i);
			}
			if (F_LEN == 1) {
				$i	= "0"$i;
			}
			chk_words($i);
			WORD[i]		= $i;
		}
	}
	END {
		if (ERR_CNT > 0) {
			printf("\nETHER_ADD=;\n");
			exit 255;
		}
		printf("ETHER_ADD=\"");
		for (y=1; y<F_CNT; y++) {
			printf("%s:", WORD[y]);
		}
		printf("%s\";\n", WORD[F_CNT]);		
	}'`;
}
			
#
# Update the client init file with the IP address of this (the server) 
# machine. The client does NOT have gethostbyname() lookup functionality, so
# it is essential that the IP is hardcoded into the init file.
#
Update_CLInit(){
	INIT_FILE=${TFTP_DIR}/${TFTP_ROOT}/bin/init;
	[ -z "${SERVER_IP}" ] && Fatal "Server IP address is not set.";
	Mod_File ${INIT_FILE} "${SIP_VAR}" "\"${SERVER_IP}\";";
	case ${?} in
		0)	echo -e "\nUpdated.\n";;
		1)	cat ${INIT_FILE} | egrep "${SERVER_IP}" >/dev/null;
			if [ ${?} -ne 0 ];	then
				Error "${INIT_FILE} config may be incorrect.";
			else
				echo -e "\nDone.\n";
			fi;;
		2)	Fatal "Unknown error while modifying: ${INIT_FILE}.";;
	esac
}

#
# Get Ethernet Adress.
#
Get_EtherAdd(){
	ETH_INU=`cat ${ETHERS} | egrep -v "^#" | egrep -w "${XTERM_NAME}"`;
	case ${?} in
		0)	return 0;;

		1)	Totty "";;

		*)	Fatal "${ETHERS} check failed.";
	esac

	cat > /dev/tty <<- EO_EINFO

        Please input the hardware ethernet address (MAC) of the system
        which is to be configured as "${XTERM_NAME}". You can see the
        ethernet address when the machine is first powered on, in the
        initial banner information which displayed at the top of the
        screen. The ethernet address will look something like this:- 

                             08:00:20:01:2A:3F

	EO_EINFO

	while [ "${ETHER_ADD:-NoTSeT}" = "NoTSeT" ];	do
		echo -n "	Ethernet Address: ";
		read ETHER_ADD;
		Check_EtherAdd "${ETHER_ADD}";
	done

	Totty "Updating ethers file: ${ETHER_ADD} ${XTERM_NAME}";
	Update_Net_File ${ETHERS} "${ETHER_ADD}" "${XTERM_NAME}" "${DNS_DOM}";
	return ${?};
}

#################
#
# main()
#
#################
#
Check_UID;
#
# If the package has been properly installed, all of these file & dir
# checks should pass.
#
Totty "Checking File/Directory Access...";
for DIR in ${DIR_LIST};	do
	Check_Dir ${DIR};
	[ ${?} -ne 0 ] && Fatal "Unable to use directory: ${DIR}";
done
for FILE in ${FILE_LIST};	do
	Check_RWA ${FILE};
	[ ${?} -ne 0 ] && Fatal "Bad R/W access on file: ${FILE}";
done

Get_Dom;
ID_Server;
Get_Hostname;
Totty "Checking for existing ${HOSTS} entries...";
Check_Hostname;

Get_EtherAdd;

Totty "Updating the RARP table.";
Run_RARP ${ETHERS};

Totty "Creating client filesystem and boot links...";
Link_BootFile "${TFTP_DIR}" "${HEX_IP}" \
	"${XTERM_IP}" "${TFTP_KERN}" "${TFTP_ROOT}";
[ ${?} -ne 0 ] && Fatal "${TFTP_DIR}: Client update failed.";

Totty "Updating the XDM config files...";
##
## Do NOT update the servers file. This is only needed for (non-Linux)
## clients which do not understand XDMCP.
##
## Update_Xservers "${X_SERVERS}" "${XTERM_NAME}";
## [ ${?} -ne 0 ] && Error "${X_SERVERS}: File update failed. Please check.";
##

XSETUP="Xsetup-${XTERM_NAME}_0";
Update_XDM "${XDM_CONFIG}" "${XDM_DIR}" \
	"${XTERM_NAME}" "${XSETUP}" "${DNS_DOM}";
[ ${?} -ne 0 ] && Error "${XDM_CONFIG}: File update failed. Please check.";

Crt_Xsetup "${XDM_DIR}/${XSETUP}" "${XSU_TEMPL}";
[ ${?} -ne 0 ] && \
	Error "${XSETUP}: File creation failed. Please create manually.";

Totty "Checking the SPARC-Linux tree server specification...";
Update_CLInit;

Re_Init "xdm";

Totty "Client add completed successfully.";
exit 0;
