#!/bin/bash -vx

# Get desired run level
runlevel="$1"

# Set the path.
PATH='/usr/bin:/usr/sbin:/bin:/sbin'

# File for storing the random seed between sessions.
random_seed='/var/run/random-seed'

echo 'Saving random seed'
chmod 600 $random_seed
dd if=/dev/urandom of=$random_seed count=1 bs=512 2>/dev/null

echo 'Stop inetd, atd, crond, logd, syslogd'
killall inetd
killall atd
killall crond
killall klogd
killall syslogd

if [ "$runlevel" != '2' ]; then
 echo 'Sending all processes the TERM signal...'
 kill -15 -1
 sleep 5
 echo 'Sending all processes the KILL signal..'
 kill -9 -1
fi

if [ "$runlevel" = '0' -o "$runlevel" = '6' ]; then
 echo 'Turn off swap, unmount file systems.'
 swapoff -a
 umount -a -f 
 mount -n -o remount,ro /

 if [ "$runlevel" = '0' ]; then
  echo 'Good night.'
  poweroff
 else 
  echo 'See ya soon.'
  reboot
 fi
fi

# If we make it through here, then we have runlevel 1 or 2.
# Everything needed for runlevel 1 is done first. Then optionally
# runlevel 2 initialisation is performed.

echo 'Initializing random number generator'
if [ -f $random_seed ]; then
 cat $random_seed >/dev/urandom
else
 touch $random_seed
fi

if [ "$runlevel" = '1' ]; then
 echo 'Switch to single user mode'
 exec init -t1 S
fi

if [ "$runlevel" = '2' ]; then

 echo 'Config network devices lo and eth0, add default route'
 ifconfig lo inet 127.0.0.1 netmask 255.255.255.0 broadcast 127.255.255.255
# ifconfig eth0 inet 130.198.41.98 netmask 255.255.255.0 broadcast 130.198.41.255
# route add default 130.198.41.1

 echo 'Start daemons'
 syslogd -m 0
 klogd

 crond
 atd

 inetd

 echo 'Configure trackpad'
 trackpad notap
 gpm -t BusMouse

 rm -f /etc/issue	# rungetty doesn't like /etc/issue
 rm -f /etc/issue.net

fi

