#!/bin/rc
# cpurc - cpu server startup
ifs='	 
'
path=(/$cputype/bin /rc/bin .)		# in case #ec/path is wrong for us
boottime=`{date}
boottime=$"boottime
echo $boottime

# truncated ndb files can keep systems from starting; recover from backup
if (~ $sysname fs cpu consoles) @ {
	cd /lib/ndb
	for (f in local common coll)
		if (! test -s $f) {
			cp backup/$f .	# recover truncated ndb file
			bind ../ndb.backup/$f $f
		}
}

# cs sets /dev/sysname
ndb/cs
sysname=`{cat /dev/sysname}

# sysname sanity checks
if (~ $#sysname 0 || ~ $sysname '') {
	sysname = helix			# default
	echo -n $sysname >/dev/sysname
}
prompt=($sysname^'# ' '	')

# get rid of need for dirs in /n
mntgen -s slashn && chmod 666 /srv/slashn

. dot

# complete namespace
9fs main  >[2]/dev/null &
9fs other >[2]/dev/null &
sleep 0.3

dot /cfg/$sysname/namespace >[2]/dev/null
# can't just do this. /cfg/$sysname/namespace mightn't exist, rc would bail out.
# dot /lib/namespace >[2]/dev/null

# parallelism for mk
NPROC = `{wc -l </dev/sysstat}

usbstart
# site-specific startup
listener=()
. /rc/bin/cpurc.local

# cpu-specific startup
# if it runs aux/listen, it must first run ndb/dns.
if(! test -e '/env/*envloaded') {	# loaded directly without 9boot?
	echo -n loading /cfg/pxe...
	. loadcfgpxe
}
dot /cfg/$sysname/cpurc

# if we're not a server, start a dns resolver
# if(! test -e /srv/dns && ! test -e /env/dns) {
if(! test -e /srv/dns) {
	echo -n dns...
	await 2 ndb/dns		# -rF
}

# keep other bootes processes from creating capabilities (optional).
# don't remove it to see if ssh2 will work with it present.
# rm '#¤/caphash' > /dev/null >[2=1]

# start up internet if we don't already have an address
if(! grep u /net/ipselftab | grep -sv 127.0.0.1) {
	echo -n ipconfig for ip...
	ip/ipconfig
}
if not if (~ $sysname pi) # in case on net 10 & answered by fw | airport extreme
	ip/ipconfig
if(! grep -s 127.0.0.1 /net/ipselftab) @ {
	echo -n loopbacks...
	ip/ipconfig loopback /dev/null 127.1
	ip/ipconfig loopback /dev/null ::1 /128
} &

# correct and maintain stable, accurate time
if(! ps|grep -s timesync) {
	echo -n timesync...
	starttimesync &
}

# start listeners if it hasn't already been done (dicey check; auth can be slow)
if(! ~ $listener yes && ! netstat -n |
    grep -s '^tcp.*Listen.* (7|9|21|22|23|25|110|113|565|993|17007|17009|17010|17013) .*') {
	echo -n listen...
	aux/listen &	# -q
}

# reboot cpu server if we lose the file server; needs time already set
if (! ~ $sysname fs)
	aux/reboot &

# cpu-specific late startup
dot /cfg/$sysname/cpustart

# prevent killing specific processes when out of memory.
# processes started via listen must be killable, so exclude listen.
dontkill '^(ipconfig|factotum|mntgen|venti|fossil|cs|dns|reboot)$' &

# log boot and kernel information
kern=`{ls -ld `{kern}}
echo $"boottime $sysname $terminal $"kern >>/sys/log/boot
echo $terminal $"kern
echo -n `{date} ' '; uptime
kmesg.boot &
exit ''
