#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-only

. /etc/init.d/installer-functions

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

console=tty0
term=vt102
interactive=1
bash_shell=0
atexit=reboot
OLDIFS="$IFS"
IFS="
"

xen_commandline() {
  xl info xen_commandline
}

# Spaces separate arguments except for spaces enclosed by a pair of single or
# double quotes.
args=$(cmdline | sed -e s'/ *$//' -e "s/'\([^']*\)'/\"\1\"/g" -e 's/\("\([^"]*\)"\)* \+/\2\n/g')
set --
for arg in $args; do
  copy=1
  case "$arg" in
    answerfile=* | rt_answerfile=* | answerfile_generator=*)
      interactive=0;;
    console=*)
      console=${arg#console=};;
    term=*)
      term=${arg#term=};;
    bash-shell | shell)
      bash_shell=1
      interactive=0
      copy=0;;
    atexit=*)
      atexit=${arg#atexit=}
      copy=0;;
    blacklist=* | enable-ide | extramodules=*)
      copy=0;;
    make-ramdisk=*)
      [ -z "$ramdisk_done" ] && /opt/xensource/installer/S05ramdisk start
      ramdisk_done=1
      copy=0;;
    sshpassword=* | start=*)
      copy=0;;
  esac
  [ $copy -eq 1 ] && set -- "$@" "--$arg"
done

if [ $started_by_systemd -eq 1 ]; then
  # Started by systemd, without TTY. This script will invoke itself
  # via agetty to connect one or more TTYs to it.

  # Run trigger followed by settle to wait for slow storage devices
  # to appear.
  udevadm settle --timeout=180
  udevadm trigger
  udevadm settle --timeout=180

  # mount xenfs if not mounted
  if [ ! -e /proc/xen/xenbus ]; then
    mount -t xenfs xenfs /proc/xen
  fi

  # disable printk on the screen
  echo 1 > /proc/sys/kernel/printk

  for arg in $args; do
    case "$arg" in
      console=*)
        c=${arg#console=}
        if [ $c == $console -o $interactive -eq 1 ]; then
          b=9600
          t=linux
          case "$c" in
            hvc*|ttyS*)
            xencon=`expr "$(xen_commandline)" : '.*\(com.=[^ ]*\)'`
            co=`expr "$c" : '\(ttyS.*\),'`
            br=`expr "$xencon" : 'com[0-9]*=\([0-9]*\)'`
            [ -n "$co" ] && c=$co
            [ -n "$br" ] && b=$br
            t=$term;;
          esac
          setsid /sbin/agetty -n -l $0 $c $b $t &
        fi
    esac
  done

else
  # Here we have been invoked from agetty (a few lines above), or
  # this script was manually invoked, presumably from a terminal.
  # Either way, we have a valid TTY.

  if [ $bash_shell -eq 1 ]; then
    echo "Exiting this shell will run the installer:"
    echo " /opt/xensource/installer/init" "$@"
    echo "---"
    IFS="$OLDIFS" /bin/bash
  fi

  [ $atexit = reboot ] && extra_args=--reboot
  /opt/xensource/installer/init "$@" $extra_args
  [ $atexit = shell ] && IFS="$OLDIFS" /bin/bash
  [ $atexit = poweroff ] && poweroff
fi

