#!/bin/sh 
#@(#)HP X station Admin Scripts
#
# dobootpstuff	Set up bootptab entries for X station
#

ip2bin ()	# ip addr to 32 digit binary
{
  BIN=""; D=""
  DIGITS=`echo $1 | sed 's/[.]/ /g'`
  for D in $DIGITS
  do
    WKBIN=""
    for TIMES in 1 2 3 4 5 6 7 8
    do
      if [ $D = "1" -a "$TIMES" = "8" ]
      then
        WKBIN=`echo "1${WKBIN}"`
        break
      else
        REM=`expr $D % 2`
        WKBIN=`echo "${REM}${WKBIN}"`
        D=`expr $D / 2`
      fi
    done
    while [ "`echo $WKBIN | wc -c`" -lt "9" ]
    do
      WKBIN=`echo "0${WKBIN}"`
    done
    BIN=${BIN}${WKBIN}
  done

  echo $BIN
}

hex2bin ()	# hexadecimal to 32 digit binary
{
  HEXNUM=$1; BIN=""
  for POS in 8 7 6 5 4 3 2 1
  do
    HEXDIG=`echo $HEXNUM | cut -c $POS,$POS`
    case $HEXDIG in
      0)   BIN=`echo "0000${BIN}"`;; 1)   BIN=`echo "0001${BIN}"`;;
      2)   BIN=`echo "0010${BIN}"`;; 3)   BIN=`echo "0011${BIN}"`;;
      4)   BIN=`echo "0100${BIN}"`;; 5)   BIN=`echo "0101${BIN}"`;;
      6)   BIN=`echo "0110${BIN}"`;; 7)   BIN=`echo "0111${BIN}"`;;
      8)   BIN=`echo "1000${BIN}"`;; 9)   BIN=`echo "1001${BIN}"`;;
      a|A) BIN=`echo "1010${BIN}"`;; b|B) BIN=`echo "1011${BIN}"`;;
      c|C) BIN=`echo "1100${BIN}"`;; d|D) BIN=`echo "1101${BIN}"`;;
      e|E) BIN=`echo "1110${BIN}"`;; f|F) BIN=`echo "1111${BIN}"`;;
      "")  ;; *)  echo "non-hex digit in input"; exit 1 ;;
    esac
  done

  while [ "`echo $BIN | wc -c`" -lt "33" ]
  do
     BIN=`echo "0${BIN}"`
  done
  echo $BIN
}

bitand ()	# bitwise *and* of 2 32 digit binary numbers
{
  NUM1=$1; NUM2=$2; POS=1; RES=""
  while [ "$POS" -lt "33" ]
  do
    DIG1=`echo $NUM1 | cut -c $POS,$POS`
    DIG2=`echo $NUM2 | cut -c $POS,$POS`
    if [ "$DIG1" = "1" -a "$DIG2" = "1" ]
    then
      RES=${RES}1
    else
      RES=${RES}0
    fi
    POS=`expr $POS + 1`
  done
  echo $RES
}

swizzle()	# convert ethernet addr to 802.5 format
{
  NEWUHATAG=""
  for BYTE in 0 1 2 3 4 5 
  do
    for HEXDIGIT in 2 1
    do
      POS=`expr $BYTE \* 2 + $HEXDIGIT`
      NEXTHEXDIGIT=`echo $1 | cut -c $POS,$POS`
      case $NEXTHEXDIGIT in
	0) NEXTHEXDIGIT=0 ;; 1) NEXTHEXDIGIT=8 ;; 2) NEXTHEXDIGIT=4 ;;
	3) NEXTHEXDIGIT=c ;; 4) NEXTHEXDIGIT=2 ;; 5) NEXTHEXDIGIT=a ;;
	6) NEXTHEXDIGIT=6 ;; 7) NEXTHEXDIGIT=e ;; 8) NEXTHEXDIGIT=1 ;;
	9) NEXTHEXDIGIT=9 ;; a) NEXTHEXDIGIT=5 ;; b) NEXTHEXDIGIT=d ;;
	c) NEXTHEXDIGIT=3 ;; d) NEXTHEXDIGIT=b ;; e) NEXTHEXDIGIT=7 ;; 
	f) NEXTHEXDIGIT=f ;; *) echo non-hex number; exit 1 ;;
      esac
      NEWUHATAG="${NEWUHATAG}${NEXTHEXDIGIT}"
    done
  done
 echo $NEWUHATAG
}

NFS=no

wantstoquit()		# function to make sure user really wants to quit
{
	cat <<EOF


The X station information has been added to the hosts database only.
Quitting the X station addition at this point means the X station will
not boot unless the following are completed:

 1) Re-run this X station addition and finish the configuration (recommended).

 2) Manually edit the required system files to set up the X station to boot 
    properly (refer to the Technical Reference Manual for HP X stations).

 3) Enter the network parameters manually through the X station
    network config screen."

EOF
	$ECHO "Do you still want to quit at this time? [y|n] (n): $NL"
	read REPLY 
	case $REPLY in
	y|Y|yes|YES|Yes)
		return 0
		;;
	*)
		return 1
		;;
	esac
}

#
# get the LAN hardware address
#
while [ 0 ]
do
	getuhatag
	case $? in
	    0)
		break
		;;
	    1)
		echo "No changes were made to bootptab."
		exit 1
		;;
	  100)
		wantstoquit
		if [ $? -eq 0 ]
		then
			exit 100
		fi
	esac
done

UHATAG=`cat $TMP/UHATAG`
HWTYPE="ether"

#
# Convert the ether UHATAG to token ring format if necessary
#

if [ $OS = "hp" ]
then
  INTERFACES=`netstat -in | sed '1d' \
	| awk '$4 !~ /^127/ && $4 ~ /[0-9]+[.]/ {print $1}'`

  for INTERFACE in $INTERFACES
  do
    LANCONFIG=/etc/lanconfig
    if [ -x $LANCONFIG ]
    then
      $LANCONFIG $INTERFACE 2>&1 | egrep -i '(802[.]5)|(8025)' > /dev/null
      if [ $? -eq 0 ]
      then
        TOKENRING="possible"
      fi
    fi
  done
else
  if [ $OS = "sun4" -o $OS = "sun5" ]
  then
    INTERFACES=`/sbin/ifconfig -a | egrep 'flags=' | awk '{ print $1}' | sed 's/:$//'`
    if [ "$INTERFACES" != "" ]
    then
      for INTERFACE in $INTERFACES
      do
        echo $INTERFACE | egrep '^tr' > /dev/null
        if [ $? -eq 0 ]
        then
          TOKENRING="possible"
        fi
      done
    fi
  fi
fi


ISTOKEN="false"
  
if [ "$TOKENRING" = "possible" ]
then
  for INTERFACE in $INTERFACES
  do
    if [ $OS = "hp" ]
    then
      if [ -x "$LANCONFIG" ]
      then
        $LANCONFIG $INTERFACE 2>&1 | egrep -i '(802[.]5)|(8025)' > /dev/null
        if [ $? -ne 0 ]
        then
	  continue
        fi
      fi
    else
      if [ $OS = "sun4" -o $OS = "sun5" ]
      then
        echo $INTERFACE | egrep '^tr' > /dev/null
        if [ $? -ne 0 ]
        then
          continue
        fi
      fi
    fi

    XTERMBINIP=`ip2bin $IPADDR`
    IFIPADDR=`ifconfig $INTERFACE | awk '$3 == "netmask" {print $2}'`
    IFMASK=`ifconfig $INTERFACE | awk '$3 == "netmask" {print $4}'`
    IFBINIPADDR=`ip2bin $IFIPADDR`
    IFBINMASK=`hex2bin $IFMASK`
  
    THISNETWORK=`bitand  $IFBINMASK $IFBINIPADDR`
    XTERMNETWORK=`bitand  $IFBINMASK $XTERMBINIP`

    if [ "$XTERMNETWORK" = "$THISNETWORK" ]
    then
      ISTOKEN="true"
      case $UHATAG in
        #
        # removed. It's being done in server 
        #
        #080009*) UHATAG=`swizzle $UHATAG` ;;   # not right format, diddle it
        *) ;;			                 # already right format
      esac
      HWTYPE="tr"
      break
    fi
  done
fi

#
# get the subnet mask and gateway
#
while [ 0 ]
do
	masks
	case $? in
	    0)
		break
		;;
	    1)
		echo "No changes were made to bootptab."
		exit 1
		;;
	  100)
		wantstoquit
		if [ $? -eq 0 ]
		then
			exit 100
		fi
	esac
done

SUBNETMASK=`cat $ADMINDIR/SUBNETMASK`
GATEWAY=`cat $ADMINDIR/GATEWAY`

#
# get confirmation of info before updating bootptab
#
echo ""
echo ""
echo ""
echo ""
echo "You have entered the following network parameters for this X station:"
echo ""
echo "Name:				$XTNAME"
echo "IP address:			$IPADDR"
echo "LAN hardware address:		$UHATAG"
echo "Subnet mask:			$SUBNETMASK"
echo "Default gateway IP address:	$GATEWAY"
echo ""
echo ""
echo ""
echo ""

while [ 0 ]
do
	$ECHO "Are these correct? [y|n|?] (y): $NL"
	read REPLY 
	case $REPLY in
	y|Y|yes|YES|Yes|"")
		break
		;;
	\?)
		cat <<EOF

If you answer yes to this question an entry containing these network
parameters will be added to $BOOTPTABLE.

If you answer no to this question, you will be given a chance to
re-enter the data.

EOF
		continue
		;;
	*)
		exit 98
		;;
	esac
done


if [ -f $CONFIGDIR/sample.cfg ]
then
  CONFIGFILE=sample.cfg
else
  CONFIGFILE=$XTTYPE.cfg
fi

RNAME=`echo $NAME | awk -F\. '{print $1}'`
DT144TAG=$RNAME.cfg
CFGFILE=$CONFIGDIR/$DT144TAG

#
# Calculate length of vendor info to see if we need to
# omit domain name and/or DT144 tag
#
NODOMAIN="false"
NODT144TAG="false"
if [ "`echo $XTNAME $DT144TAG | wc -c`" -gt 40 ]
then
  NODOMAIN="true"
  if [ "`echo $RNAME $DT144TAG | wc -c`" -gt 40 ]
  then
    NODT144TAG="true"
  fi
fi


touch $BOOTPTABLE
if [ $NODOMAIN = "false" ]
then
  rmbootpentry $XTNAME < $BOOTPTABLE > $TMP/bootptab 2> /dev/null
else
  rmbootpentry $RNAME < $BOOTPTABLE > $TMP/bootptab 2> /dev/null
fi

if [ $? -eq 0 ]
then
  if [ -s $TMP/bootptab ]
  then
	echo ""
	echo "Removed existing entry for $XTNAME from $BOOTPTABLE."
  else
	echo ""
	echo "Removal from $BOOTPTABLE failed."
        exit 1
  fi
fi

echo ""				>> $TMP/bootptab

if [ $NODOMAIN = "false" ]
then
  echo "$XTNAME:\\"		>> $TMP/bootptab
  if [ $DOMA != "NONE" ] 
  then  
    echo "	ds=$DOMA:\\" 	>> $TMP/bootptab
  fi
else
  echo "$RNAME:\\"		>> $TMP/bootptab
fi


#
#
# Does bootp daemon seem to understand the ba tag
# 1) so we may broadcast queries using bootpquery
# 2) and put ba tags in bootptab
#
#
strings $BOOTPD | egrep 'ba -- broadcast address' > /dev/null
if [ $? -eq 0 ]
then
  #
  # yes, it seem to know about it, make a note for later
  #
  UNDERSTANDSBA="true"
else
  UNDERSTANDSBA="false"
fi


#
# can we use ba tag?
#
if [ "$UNDERSTANDSBA" = "true" ]
then
  echo "	ba:\\"		>> $TMP/bootptab
fi


echo "	hn:\\"		>> $TMP/bootptab

DHDTAG="/usr/lib/X11/700X/bin"


echo "	ht=$HWTYPE:\\"		>> $TMP/bootptab
echo "	ha=$UHATAG:\\" 		>> $TMP/bootptab
echo "	ip=$IPADDR:\\" 		>> $TMP/bootptab

if [ \( "$OS" = "sun4" -o "$OS" = "sun5" \) -a \( $ALTLINK != "none" \) ]
then
  if [ ! -f $DHDTAG/modules.ld -a -h $ALTLINK ]
  then
    echo "	bf=${ALTLINK}/:\\" 		>> $TMP/bootptab
  else
    echo "	hd=$DHDTAG:\\" 		>> $TMP/bootptab
  fi
else
  if [ "$OS" = "hp10" ]
  then 
    echo "	bf=${XTHOME}/:\\" 	>> $TMP/bootptab
  else 
    echo "	hd=$DHDTAG:\\" 		>> $TMP/bootptab
  fi 
fi


if [ $GATEWAY != "none" ]
then
    echo "	gw=$GATEWAY:\\" 	>> $TMP/bootptab
fi

if [ $SUBNETMASK != "none" ]
then
    echo "	sm=$SUBNETMASK:\\" 	>> $TMP/bootptab
fi

if [ $NODT144TAG = "false" ]
then
  echo "	T144=\"$DT144TAG\":\\" 	>> $TMP/bootptab
fi

echo "	vm=rfc1048" 		>> $TMP/bootptab

echo ""
echo "$XTNAME added to $BOOTPTABLE."

cp $TMP/bootptab $BOOTPTABLE 

if [ $? != 0 ] 
then  
	echo "Error: Modification of $BOOTPTAB failed"
	exit 1
fi

rm $TMP/bootptab

#
# Do we have our own disks?
#
egrep "^/" $MOUNTTABLE > /dev/null 2>&1
RET1=$?

#
# Don't ask about NFS if 700/X
#
if [ $XTTYPE != 700X ]
then

#
# nfsd running?
#

echo ""

if [ $OS = "sun5" ]
then
  # 
  # Can't seem to make "ps -ef" work reliably on this OS
  #
  ps -e | awk '$4 == "nfsd" {print $4 }' | grep . > /dev/null 2>&1
else
  $PSCMD | fgrep -v "fgrep" | fgrep "nfsd" > /dev/null 2>&1
fi

RET2=$?

if [ $RET1 -ne 0 -o $RET2 -ne 0 ] 
then
  echo "nfsd is not running or there are no local file systems... NFS cannot be used."
else
  echo "NFS is running on this computer ..."
  while true
  do
    xtutil_can-mount $SHORTNAME $XTHOME
    if [ $? -eq 0 ]
    then
      echo and $SHORTNAME seems to be able to mount $XTHOME
      NFS=yes
      break
    fi
    $ECHO "Use $HOSTNAME as NFS server for this X station? [y|n|?] (y): $NL"
    read SEL
    echo ""
    case $SEL in
 	y|Y|YES|yes|"")

      for DIR in $NFSDIRS
      do

	#
	# avoid calling donfs if fs already covered
	# (I know, it only works for fs adjacent in $NFSDIR)
        #
        NEWFS=`wherelives $DIR` 

        if [ "$NEWFS" != "$OLDFS" ]
        then
	  donfs $DIR
	  if [ $? -eq 0 ]
	  then
	    NFS=yes
	  else
	    NFS=no 
	    break
	  fi
        fi

        OLDFS=$NEWFS 
      done

      break
      ;;
    \?)
      echo "

NFS is a faster method than TFTP for downloading the server code and fonts.
Some X station local clients can only access resource files through NFS.

"
	      if [ $OS = "hp" ]
	      then
echo "Also using NFS allows the X station to access the workstation X server fonts."
	      fi
	      echo "
Refer to the Technical Reference Manual for HP X stations for more
information.

"
	      ;;
	  *)
	      break
	      ;;
	esac
    done
fi

fi	# 700/X

echo ""
if [ -f $CONFIGDIR/$RNAME.cfg ]
then
	echo "Using existing configuration file $RNAME.cfg."
else
	 touch $CFGFILE
	 echo "#################################################" > $CFGFILE
	 echo "# Remote Configuration file for X station $NAME" >> $CFGFILE
	 cat $CONFIGDIR/$CONFIGFILE                              >> $CFGFILE
	 chmod 644 $CFGFILE
	 echo "Configuration file $CFGFILE created."
fi

if [ $NFS = "yes" ]
then
  cat > $TMP/sed.$$ <<EOF
/^[# 	]*Access Mechanism/c\\
Access Mechanism = NFS       # Transfer protocol, TFTP or NFS.
EOF
  sed -f $TMP/sed.$$ $CFGFILE > $TMP/cfg
  rm $TMP/sed.$$
  cp $TMP/cfg $CFGFILE 
  rm $TMP/cfg

  cat > $TMP/sed.$$ <<EOF
/^[# 	]*SAVE_CONFIG/c\\
SAVE_CONFIG                       # save config in EEPROM
EOF
  sed -f $TMP/sed.$$ $CFGFILE > $TMP/cfg
  rm $TMP/sed.$$
  cp $TMP/cfg $CFGFILE 
  rm $TMP/cfg

  echo ""
  echo "Most HP X stations will automatically attempt to boot using NFS."
  echo "Some older models may need to be manually configured to do this."
  echo "Please make sure that terminal is set to boot using NFS, eg"
  echo "On terminal: <press F12> <click Network> <click tftp -> NFS> <click Save/OK>"
  $ECHO "enter <return> to continue: $NL"
  read REPLY
  echo ""
fi

#
# Check if /etc/services (map?) is OK
#
if [ $NISS = "true" ]
then
  ypcat services | egrep '^bootp[cs]' > /dev/null
  if [ $? -ne 0 ]
  then
    echo ""
    echo "Modifications are needed in order for bootp to bootstrap the X station."
    echo "You need to add lines similar to the ones below to the"
    echo "services map (=/etc/services) on NIS master $NISSMASTER:"
    echo $BOOTPCLINE
    echo $BOOTPSLINE
    echo "A \"$MAKESCMD\" command will be needed to push the new map."
    echo "Details may vary. Please consult your NIS documentation."
    echo ""
    exit 97
  fi 

###############################################
#
# Are we running NIS+ for services?
#
#################################################

elif [ $NISPLUSS = "true" ]
then
  #
  ##################################
  # yes, do we need to update maps?
  ##################################
  #
  nismatch name=bootps services.org_dir > /dev/null
  if [ $? -ne 0 ]
  then
    # 
    ################################################
    # we need to update maps, better ask permission
    ################################################
    # 
    while true 
    do
      echo ""
      echo ""
      echo "bootp service not in NIS+ database"
      echo ""
      CMD="echo bootps 67/udp | /usr/lib/nis/nisaddent -a services"
      echo "Execute the command \"$CMD\""
      echo "to add bootp service to the NIS+ services map ? [y|n] (y): \c"
      SEL=`line`
      case $SEL in
        y*|Y*|"")

	  echo $CMD | /bin/sh

          nismatch name=bootpc services.org_dir > /dev/null
          if [ $? -ne 0 ]
          then
            CMD="echo bootpc 68/udp | /usr/lib/nis/nisaddent -a services"
	    echo $CMD | /bin/sh
          fi

	  break
          ;;
        n|N|NO|no)
	  break
          ;;
        *)
	  :
          ;;
      esac
    done
  fi
else

  egrep '^bootp[cs]' /etc/services > /dev/null
  if [ $? -ne 0 ]
  then
    echo ""
    echo "Modifications are needed in order for bootp to bootstrap the X station."
    echo "You need to add lines similar to the ones below to the"
    echo "services map (=/etc/services) on NIS master $NISSMASTER:"
    echo $BOOTPCLINE
    echo $BOOTPSLINE
    echo "A \"$MAKESCMD\" command will be needed to push the new map."
    echo "Details may vary. Please consult your NIS documentation."
    echo ""
    exit 97
  fi
fi


#
# Now check if we can receive boot parameters from bootpd
# If there are problems, inetd may need to be restarted
#


# SCO ODT 2.x bootpd and others do not support the ba tag
# so don't do bootpquery thing below
#
if [ "$UNDERSTANDSBA" = "false" ]
then
  exit 0
fi

#
# On 10.0 the rbbotd daemon may be listening on
# udp port 67/68 for boot requests from older diskless workstations.
#
RBOOTDPID=""
if [ "$OS" = "hp10" ]
then
  RBOOTDPID=`ps -e | awk '$NF ~ "rbootd" {print $1}'`
  if [ "$RBOOTDPID" != "" ]
  then
    kill "$RBOOTDPID"
    sleep 2
  fi
fi


if [ "$HWTYPE" = "tr" ]
then
  if [ "$OS" = "hp10" ]
  then
    #
    # don't use the -s flas as 10.10 and beyond does not deal well with it
    #
    $BOOTPQUERY $UHATAG ieee802  2>&1 \
	|  egrep -i 'IP Address' /dev/null 2>&1
  else
    $BOOTPQUERY $UHATAG ieee802 -s $HOSTNAME 2>&1 \
	|  egrep -i 'IP Address' /dev/null 2>&1
  fi
else
  if [ "$OS" = "hp10" ]
  then
    #
    # don't use the -s flas as 10.10 and beyond does not deal well with it
    #
    $BOOTPQUERY $UHATAG 2>&1 \
	| egrep -i 'IP Address'  > /dev/null 2>&1
  else
    $BOOTPQUERY $UHATAG -s $HOSTNAME 2>&1 \
	| egrep -i 'IP Address' > /dev/null 2>&1
  fi
fi
RET=$?


#
# If we took rbootd down, restart it again 
#
if [ "$OS" = "hp10" -a "$RBOOTDPID" != "" ]
then
  rbootd
fi

if [ $RET -ne 0 ]
then
    cat <<EOF

No reply was received from the bootpd daemon on this computer.
Select "Check operation of bootp" from the "Installation testing"
menu of xtadm.
EOF
    $ECHO "enter <return> to continue: $NL"
    read REPLY

    exit 97
fi


exit 0
