#!/bin/bash
#
# This program is run by /hurd/init at boot time after the essential
# servers are up, and is responsible for running the "userland" parts of a
# normal system.  This includes running the single-user shell as well as a
# multi-user system.  This program is expected never to exit.
#


###
### Where to find programs, etc.
###

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

# If we lose badly, try to exec each of these in turn.
fallback_shells='/bin/sh /bin/bash /bin/csh /bin/ash /bin/shd'

# Shell used for normal single-user startup.
SHELL=/bin/sh

###


# If we get a SIGLOST, attempt to reopen the console in case
# our console ports were revoked.  This lets us print messages.
function reopen_console ()
{
  exec 1>/dev/console 2>&1 || exit 3
}
trap 'reopen_console' SIGLOST


# Call this when we are losing badly enough that we want to punt normal
# startup entirely.  We exec a single-user shell, so we will not come back
# here.  The only way to get to multi-user from that shell will be
# explicitly exec this script or something like that.
function singleuser ()
{
  test $# -eq 0 || echo "$0: $*"
  for try in ${fallback_shells}; do
    SHELL=${try}
    exec ${SHELL}
  done
  exit 127
}


# See whether pflocal is setup already, and do so if not (install case)

if ! test -e /servers/socket/1 && which settrans >/dev/null ; then
  settrans -c /servers/socket/1 /hurd/pflocal
fi

# We expect to be started by console-run, which gives us no arguments and
# puts FALLBACK_CONSOLE=file-name in the environment if our console is
# other than a normal /dev/console.

if [ "${FALLBACK_CONSOLE+set}" = set ]; then
  singleuser "Running on fallback console ${FALLBACK_CONSOLE}"
fi


###
### Normal startup procedures
###

# Parse the multiboot command line.  We only pay attention to -s and -f.
# The first argument is the kernel file name; skip that.
shift
flags=
single=
while [ $# -gt 0 ]; do
  arg="$1"
  shift
  case "$arg" in
  --*) ;;
  *=*) ;;
  -*)
    flags="${flags}${arg#-}"
    ;;
  'single')
    single="-s"
    ;;
  'fastboot'|'emergency')
    ;;
  esac
done

# Touch the first tty so that the Hurd console is certain to pick it
# and not some random other tty.
touch /dev/tty1

# Finally, start the actual SysV init.
# Pass -i to make `init' work as init, even if its PID is not 1.
/sbin/init -i ${single} -a
