#!/sbin/sh
#
#       @(#)startup.sh 1.67 99/01/25 SMI
#
# Copyright (c) 1992-1995 Sun Microsystems, Inc.  All Rights Reserved. Sun
# considers its source code as an unpublished, proprietary trade secret, and
# it is available only under strict license provisions.  This copyright
# notice is placed here only to protect Sun in the event the source is
# deemed a published work.  Dissassembly, decompilation, or other means of
# reducing the object code to human readable form is prohibited by the
# license agreement under which this code is provided to the user or company
# in possession of this copy.
#
# RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the Government
# is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the
# Rights in Technical Data and Computer Software clause at DFARS 52.227-7013
# and in similar clauses in the FAR and NASA FAR Supplement.
#
# NOTE:	run as the runlevel 234 process; invoked from the inittab; invokes
#	sysconfig with all necessary environment setup
#

SHELL=/sbin/sh
TEXTDOMAIN=SUNW_INSTALL_SCRIPTS
PATH=/sbin:/usr/sbin/install.d:/usr/openwin/bin:${PATH}
SWAP_FILE=/swap2

PLATFORM=`/sbin/uname -p`

# make home dir to a writeable place
HOME=/tmp/root
export SHELL TEXTDOMAIN PATH PLATFORM HOME

# Local Variables
KDMCONFIG_NOGUI=/tmp/root/var/tmp/kdmconfig.nogui
OWCONFIG_FILE=/tmp/root/etc/openwin/server/etc/OWconfig
RUN_WIN=1
RUN_KDM=0

#
# Search for the sysid configuration file
# on the bootparams.
#
bootparams_sysid_config()
{
	MOUNT_CONFIG_DIR=/tmp/sysid_config.$$
	mkdir ${MOUNT_CONFIG_DIR}

	#
	# Check for a 'sysid_config' bootparams entry
	#
	set -- `/sbin/bpgetfile -retries 1 sysid_config`
	if [ $1"X" != "X" ]; then
		mount -o ro -F nfs $2:$3  \
			${MOUNT_CONFIG_DIR} >/dev/null 2>&1
					 
		if [ $? -eq 0 ]; then
			if [ -f ${MOUNT_CONFIG_DIR}/sysidcfg ]; then
				cp ${MOUNT_CONFIG_DIR}/sysidcfg /etc
				chmod 0600 /etc/sysidcfg
				echo "Using sysid configuration file ${2}:${3}/sysidcfg"
				return 0
			fi
			umount ${MOUNT_CONFIG_DIR}
		fi
	fi
	rmdir ${MOUNT_CONFIG_DIR}

	return 1
}

#
# Search for the sysid configuration file
# in DHCP.
#
dhcp_sysid_config()
{
	MOUNT_CONFIG_DIR=/tmp/sysid_config.$$
	mkdir ${MOUNT_CONFIG_DIR}

	#
	# Check for a 'sysid_config' bootparams entry
	#
	set -- `/sbin/dhcpinfo SsysidCF`
	if [ $1"X" != "X" ]; then
		mount -o ro -F nfs $1  \
			${MOUNT_CONFIG_DIR} >/dev/null 2>&1
					 
		if [ $? -eq 0 ]; then
			if [ -f ${MOUNT_CONFIG_DIR}/sysidcfg ]; then
				cp ${MOUNT_CONFIG_DIR}/sysidcfg /etc
				chmod 0600 /etc/sysidcfg
				echo "Using sysid configuration file ${1}/sysidcfg"
				return 0
			fi
			umount ${MOUNT_CONFIG_DIR}
		fi
	fi
	rmdir ${MOUNT_CONFIG_DIR}

	return 1
}

#
# Search for the sysid configuration file
# on the local floppy drive.  Try to mount
# PCFS first and then UFS
#
floppy_sysid_config()
{
	MOUNT_CONFIG_DIR=/tmp/sysid_config.$$

    # Check to see if there is a floppy in the drive (silently)
    #
    /usr/bin/eject -q floppy >/dev/null 2>&1

    if [ $? -eq 0 ]; then
        # Make the mount point directory used in searching
        # for the profile
        #
        if [ ! -d ${MOUNT_CONFIG_DIR} ]; then
            mkdir ${MOUNT_CONFIG_DIR} 2>/dev/null
        fi

        # Try to mount the floppy first as PCFS, then as UFS
        #
        mount -o ro,foldcase -F pcfs /dev/diskette ${MOUNT_CONFIG_DIR} \
                            >/dev/null 2>&1
        status=$?
        if [ ${status} -ne 0 ]; then
            mount -o ro -F ufs  /dev/diskette ${MOUNT_CONFIG_DIR} \
                            >/dev/null 2>&1
            status=$?
        fi

	if [ ${status} -eq 0 ]; then
		if [ -f ${MOUNT_CONFIG_DIR}/sysidcfg ]; then
			cp ${MOUNT_CONFIG_DIR}/sysidcfg /etc
			chmod 0600 /etc/sysidcfg
			echo "Using sysid configuration file from local floppy"
			# since the sysidcfg file was copied to /etc/sysidcfg
			# we can unmount the floppy and remove the
			# mount point before returning
			umount ${MOUNT_CONFIG_DIR}
			rmdir ${MOUNT_CONFIG_DIR}
			return 0
		fi
		umount ${MOUNT_CONFIG_DIR}
	fi

	rmdir ${MOUNT_CONFIG_DIR}
	fi

	return 1
}

getcd0dev() {
    D=$1    # Device

    IFS=":"
    set -- ${D}
    # get everything up till last ":" into U
    U=$1
    shift ;
    while [ $# -gt 1 ] ; do
        U=${U}:$1
        shift ;
    done
    # now we got everything except the stuff after the last ":",
    # which we assume was just a partition letter

    # x86 & ppc use p0 device for hsfs.  sparc uses s0 device.
    # These map to :q and :a respectively under /devices/...

    if [ "${PLATFORM}" = "sparc" ]; then
        echo "${U}:b"
    else
        echo "${U}:q"
    fi
}

#
#       checkmessage raw_device fstype mountpoint
#
# Simple auxilary routine to the shell function checkfs. Prints out
# instructions for a manual file system check before entering the shell.
#
checkmessage() {
        echo ""
        echo "WARNING - Unable to repair the $3 filesystem. Run fsck"
        echo "manually (fsck -F $2 $1). Exit the shell when"
        echo "done to continue the boot process."
        echo ""
}

checkmessage2() {
        echo ""
        echo "WARNING - fatal error from fsck - error $4"
        echo "Unable to repair the $3 filesystem. Run fsck manually"
        echo "(fsck -F $2 $1). System will reboot when you exit the shell."
}


# Export net boot configuration strategy. _INIT_NET_IF is set to the
# interface name of the netbooted interface if this is a net boot.
# _INIT_NET_STRATEGY is set to the network configuration strategy.
set -- `/sbin/netstrategy`
if [ $? -eq 0 ]; then
	if [ "$1" = "nfs" -o "$1" = "cachefs" ]; then
		_INIT_NET_IF="$2"
	fi
	_INIT_NET_STRATEGY="$3"
	export _INIT_NET_IF _INIT_NET_STRATEGY 
fi

### CD into /tmp/root
cd ${HOME}

### Mount the rootfs read,write.
SWAPPART=`cat /.swappart`
/usr/sbin/fsck -F ufs -m /dev/dsk/$SWAPPART > /dev/null 2>&1
if [ $? -ne 0 ];then
	/usr/sbin/fsck -F ufs -o p /dev/dsk/$SWAPPART
	case $? in
                0|40)   # File system OK
                        ;;

                1|34|36|37|39)  # couldn't fix the file system - enter a shell
                        checkmessage "/dev/dsk/$SWAPPART" "ufs" "/"
                        /sbin/sulogin < /dev/console
                        echo "resuming system initialization"
                        ;;

                *)      # fsck child process killed (+ error code 35)
                        checkmessage2 "/dev/dsk/$SWAPPART" "ufs" "/" "$?"
                        /sbin/sulogin < /dev/console
                        echo "*** SYSTEM WILL REBOOT AUTOMATICALLY ***"
                        sleep 5
			if [ `uname -p` = "sparc" ];then
				sync;sync;reboot -- `cat /.bootdev`
			else
				sync;sync;reboot
			fi
                        ;;
	esac
fi
mount -F ufs -o remount,rw / > /dev/null 2>&1

# Determine if we are running on a multi-byte image.  If so, save the
# locale.

ENTRY=`ls /usr/lib/locale/*/LC_MESSAGES/openwin-defaultfont 2>/dev/null`
if [ -n "${ENTRY}" ]; then
	COUNT=`echo ${ENTRY} | wc -w`
	if [ ${COUNT} -eq 1 ]; then
		MB_LOC=`expr "$ENTRY" : '.*locale\/\(.*\)\/LC.*'`
		echo $MB_LOC >/tmp/.mb_locale
	fi
fi

##########
# Make sure all configuration necessary is completed in order
# to run the window system

#
# Search for the sysidtool configuration
# in the following order
#	floppy (PCFS)
#	floppy (UFS)
#	network (bootparams or DHCP)
#
#echo "Searching for sysid configuration file..."
floppy_sysid_config
if [ $? -ne 0 ]; then
	# Look for sysidcfg via DHCP only if the network is using DHCP
	if [ "X${_INIT_NET_STRATEGY}" = "Xdhcp" ]; then
		dhcp_sysid_config
	else
		bootparams_sysid_config
	fi
#	if [ $? -ne 0 ]; then
#		echo "No sysid configuration file found"
#	fi
fi


#
# Configure the frame buffer links
#
fbdev=`ls /devices\`/usr/sbin/prtconf -F 2>&1\`* 2>/dev/null`

if [ $? -ne 0 ]; then
        RUN_WIN=0
else
        set `echo ${fbdev}`
        rm -f /dev/fb
        ln -s $1 /dev/fb

        # XXX temporary
        # NOTE: Why is this temporary and what is its purpose?
        #
        cd /dev/fbs
        for nm in *
        do
                if [ ! -h /dev/$nm ]; then
                        ln -s /dev/fbs/$nm /dev/$nm
                fi
        done

        # The code below for handling leo framebuffer configuration
        # should be generalized into a callout which can be
        # used for any framebuffer

        echo ${fbdev} | grep "SUNW\,leo" >/dev/null 2>&1
        if [ $? -eq 0 ]; then
                if [ -x /etc/rc2.d/S91leoconfig ]; then
                        /etc/rc2.d/S91leoconfig
                fi
        fi

        echo ${fbdev} | grep "PFU\,aga" >/dev/null 2>&1
        if [ $? -eq 0 ]; then
                 if [ -x /etc/rc2.d/S91agaconfig ]; then
                                 /etc/rc2.d/S91agaconfig start
                 fi
        fi

        echo ${fbdev} | grep "SUNW\,afb" >/dev/null 2>&1
        if [ $? -eq 0 ]; then
                if [ -x /etc/rc2.d/S91afbinit ]; then
                        /etc/rc2.d/S91afbinit
                fi
        fi

	echo ${fbdev} | grep "SUNW\,Expert3D" >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		if [ -x /etc/rc2.d/S91ifbinit ]; then
			/etc/rc2.d/S91ifbinit start
		fi
	fi

        cd ${HOME}

        case "${PLATFORM}" in
        ppc|i386)
                RUN_KDM=1
                ;;
        esac
fi

# non-SPARC systems require the keyboard/mouse/display hardware be configured
# for the sake of creating the OWconfig file.
# To do this, we try to set the correct locale (the Intel and PPC console
# display's are 8-bit clean so this may work.
# Run kdmconfig to configure the OWconfig file.
#
# In 2.6, the existence of the OWconfig file is not enough to
# guarantee that we want to try and bring up a GUI environment.
# kdmconfig may write out an OWconfig file with values of "Unknown"
# for some of the attributes.  So, the OWconfig file check has been
# enhanced with a check for the KDMCONFIG_NOGUI file in the case that
# the OWconfig exists.
# sysidconfig runs kdmconfig, and kdmconfig will create this file
# in the case that the GUI environment should not be set up.
#
if [ "${RUN_KDM}" -eq 1 ]; then
  LANG=`grep LANG /tmp/root/etc/default/init 2>/dev/null | \
   		sed -e '/^#/d' -e 's/.*=//'`
  if [ -n "${LANG}" ]; then
    export LANG
  else
    LC_MESSAGES=`grep LANG /tmp/root/etc/default/init 2>/dev/null \
     		| sed -e '/^#/d' -e 's/.*=//'`
    if [ -n "${LC_MESSAGES}" ]; then
      export LC_MESSAGES
    fi
  fi
  TERM=sun-color;export TERM
  /usr/sbin/sysidconfig
  ### Check for symlink'd OWconfig file
  if [ ! -h /etc/openwin/server/etc/OWconfig ];then
    if [ -f ${OWCONFIG_FILE} ];then
      cd /etc/openwin/server/etc
      #kdmconfig killed the symlink
      mv OWconfig $OWCONFIG_FILE
      ln -s  ../../../../tmp/root/etc/openwin/server/etc/OWconfig OWconfig
      cd /tmp/root
      ### Bugid's 4270374 and 4270445, 
      ### when 4270445 is fixed this can be deleted.
      DEPTH=`grep defdepth ${OWCONFIG_FILE} | sed -e 's:defdepth=::g' -e 's:\"::g'`
      if [ $DEPTH -lt 8 ];then
	RUN_WIN=0
      fi
    fi
  fi
  ### Check to see if windowing is available
  if [ ! -f ${OWCONFIG_FILE} ]; then
    RUN_WIN=0
  elif [ -f ${KDMCONFIG_NOGUI} ]; then
    RUN_WIN=0
  fi
fi
#
# Remove un-needed /dev symlinks, since each one uses a page in tmpfs.
#
rm -f /tmp/dev/pts/4? /tmp/dev/pts/3? /tmp/dev/pts/2? /tmp/dev/pts/1?
rm -f /tmp/dev/win1?? /tmp/dev/win[1-9]? /tmp/dev/win[5-9]
rm -f /tmp/dev/ptyp[5-9] /tmp/dev/ptyp[a-f]
rm -f /tmp/dev/ttyp[5-9] /tmp/dev/ttyp[a-f]
rm -f /tmp/dev/ptyq* /tmp/dev/ptyr* /tmp/dev/ttyq* /tmp/dev/ttyr*

TotalRAM=`/usr/sbin/prtconf | grep '^Memory size: ' | \
		sed -e 's/^Memory size: //' -e 's/ .*$//' `

MemUnit=`/usr/sbin/prtconf | grep '^Memory size: ' | \
		sed -e 's/^Memory size: [0-9][0-9]* //' `

case $MemUnit in
	Kilobytes) TotalRAM=`expr $TotalRAM / 1000` ;;
	Megabytes) ;;
	Gigabytes) TotalRAM=`expr $TotalRAM \* 1000` ;;
	*)	   TotalRAM=0 ;;
esac
if [ "$TotalRAM" -lt "64" ]
then
	echo "This installer requires 64M of physical memory. This system has $TotalRAM" 
	echo "See the Install Documentation for details on other installation methods"
	echo "Exiting"
	exec sh
fi

MEMSIZE=`/sbin/mem`
echo "startup available memory: ${MEMSIZE}" \
	>> /tmp/root/var/sadm/system/logs/sysidtool.log
if [ "${MEMSIZE}" -lt 6000 ]; then 
	if [ ! -f /tmp/.nowin ]; then
	        touch /tmp/.nowin 
		echo "startup: insufficient memory for window system" \
			>> /tmp/root/var/sadm/system/logs/sysidtool.log
		echo "Warning: Insufficient memory to start window system."
	fi
fi


# Start up the window system unless the display device cannot be
# determined or the install process with explicitly booted with
# the "-nowin" option.
#
# The window system is necessary to display Internationalized messages.
#
# NOTE:	At this point localization may be set
#
if [ "${RUN_WIN}" -eq 0 -o -f /tmp/.nowin ]; then
  	if [ ! -f /tmp/.nowin ];then
	  	touch /tmp/.nowin
	fi
	# run syslogd to redirect all those annoying error messages to
  	# somewhere useful, like /var/adm/message
	cp /etc/syslog.conf.webstart /etc/syslog.conf > /dev/null 2>&1
  	/etc/rc2.d/S74syslog start
  	echo "Running in command line mode"
	exec /sbin/disk0_install
else
	# if the hostname is not yet configured we need a dummy entry
	# in /etc/hosts so the window system will work
	#
	name=`uname -n`
	if [ -z "${name}" ]; then
		uname -S localhost
	fi
	
	mkdir -p ${HOME}/.dt
	
	#______________________________________________________________
	# If CD0 installation use our own openwin-init file	# cd0++
	# and start openwin without the banner screen		# cd0++
	#							# cd0++
	
	CD0_INSTALL=/tmp/.cd0_boot				
	touch $CD0_INSTALL

	swap -a ${SWAP_FILE} > /dev/null 2>&1
		
	### Going to start the CD0 windowing environment
	/sbin/setupRootDisk0 $HOME
	PATH=$PATH:/usr/openwin/bin:/usr/dt/bin; export PATH
	OPENWINHOME=/usr/openwin; export OPENWINHOME

	### This is to make sure that it is copying over the right 
	### for setup....
	### For the original startup......
	### exec sh
	/usr/openwin/bin/xinit /usr/dt/bin/Xsession -- -nobanner

fi
