#!/bin/bash
# Copyright (c) 2005-2006 XenSource, Inc. All use and distribution of this 
# copyrighted material is governed by and subject to terms and conditions 
# as licensed by XenSource, Inc. All other rights reserved.
# Xen, XenSource and XenEnterprise are either registered trademarks or 
# trademarks of XenSource Inc. in the United States and/or other countries.

###
# XEN CLEAN INSTALLER
# Startup script
#
# by Andrew Peace

# Test if started by init (or recursively by preinit)
if [ "$1" == "--" ] ; then
    started_by_init=0
else
    started_by_init=1
fi

export LVM_SYSTEM_DIR=/tmp/lvm

console=tty0
term=vt102
interactive=1
bash_shell=0
OLDIFS="$IFS"
IFS="
"
# spaces seperate arguments except for spaces enclosed by a pair of double quotes
args=$(sed -e s'/ *$//' -e 's/\(\("[^"]*"\)*\) \+/\1\n/g' /proc/cmdline)
set --
for arg in $args; do
  copy=1
  case "$arg" in
    answerfile=* | rt_answerfile=*)
      interactive=0;;
    console=*)
      console=${arg#console=};;
    term=*)
      term=${arg#term=};;
    bash-shell)
      bash_shell=1
      copy=0;;
    blacklist=* | extramodules=*)
      copy=0;;
  esac
  [ $copy -eq 1 ] && set -- "$@" "--$arg"
done

# OEM edition contains file /.oem_edition
# Note: the non-OEM edition behaves like the OEM edition if you 
# pass in "oem_edition" on the kernel command line
[ -e /.oem_edition ] && set -- "$@" "--oem_edition"

if [ "$started_by_init" == "1" ]; then
  # started by init on the console

  # force TERM if on a serial console (Xen defeats init's attempt to do this)
  case "$console" in ttyS*) export TERM=$term;; esac

  if [ $bash_shell -eq 1 ]; then
    echo "Exiting this shell will run the installer:"
    echo " /opt/xensource/installer/init" "$@"
    echo "---"
    IFS="$OLDIFS" /bin/bash
  elif [ $interactive -eq 1 ]; then
    # start clones on all other consoles
    for arg in $args; do
      case "$arg" in
        console=*)
          c=${arg#console=}
	  if [ $c != $console ]; then
	    b=9600
	    t=linux
	    case "$c" in
	      ttyS*)
		co=`expr "$c" : '\(ttyS.*\),'`
		br=`expr "$c" : 'ttyS.*,\([0-9]*\)'`
		[ -n "$co" ] && c=$co
		[ -n "$br" ] && b=$br
		t=$term;;
	    esac
	    /sbin/getty -n -l $0 $c $b $t &
	  fi
      esac
    done
  fi
fi

/opt/xensource/installer/init "$@" --reboot
