#!/bin/sh
# Run script of the getty units, with the conditions and agetty options of
# systemd's getty units:
#   getty UNIT console        container: agetty on /dev/console
#   getty UNIT vt TTY         host with /dev/tty0: agetty on the virtual terminal
#   getty UNIT serial TTY     instance of serial-getty: agetty on TTY ("!" for "/")
# An unmet condition records /run/svctl/skipped/UNIT and leaves the longrun
# down until its next start.
unit=$1 mode=$2 tty=${3:-console}
issue=/etc/issue:/etc/issue.d:/run/issue.d:/usr/lib/issue.d
container=
[ -s /run/init_env/container ] && container=1

skip() {
	mkdir -p /run/svctl/skipped
	printf '%s\n' "$1" >"/run/svctl/skipped/.$unit.$$" && mv -f "/run/svctl/skipped/.$unit.$$" "/run/svctl/skipped/$unit"
	echo "getty: $unit: skipped ($1)"
	s6-svc -O .
	exit 0
}

case $mode in
console)
	[ -n "$container" ] || skip container
	set -- --noclear --issue-file="$issue" --keep-baud 115200,57600,38400,9600 console vt220
	;;
vt)
	[ -z "$container" ] || skip '!container'
	[ -e /dev/tty0 ] || skip "no /dev/tty0"
	set -- --noclear --issue-file="$issue" "$tty" linux
	;;
serial)
	exec agetty --noclear --issue-file="$issue" --keep-baud 115200,57600,38400,9600 "$(echo "$tty" | tr '!' /)" vt220
	;;
*)
	echo "usage: getty UNIT console|vt TTY|serial TTY" >&2
	exit 100
	;;
esac
rm -f "/run/svctl/skipped/$unit"
exec agetty "$@"
