#!/bin/sh
# Instances of serial-getty like systemd's getty-generator: every active kernel
# console that is not a virtual terminal and opens as a terminal, and each
# virtualizer console that exists. An instance name is the tty with "/" as "!".
PATH=/usr/sbin:/usr/bin:/sbin:/bin
svc=/run/service/serial-getty

consoles() {
	active=$(cat /sys/class/tty/console/active 2>/dev/null) || return 0
	for c in $active; do
		if [ "$c" = tty0 ]; then
			c=$(cat /sys/class/tty/tty0/active 2>/dev/null)
			[ -n "$c" ] || continue
		fi
		[ -e "/dev/$c" ] && echo "$c"
	done
}

ttys=$(
	for c in $(consoles); do
		case $c in tty[0-9]*) continue ;; esac
		# enumerated serial ports without hardware fail on open
		stty -F "/dev/$c" >/dev/null 2>&1 </dev/null || { echo "getty-generator: /dev/$c is no working terminal" >&2; continue; }
		echo "$c"
	done
	for c in hvc0 xvc0 hvsi0 sclp_line0 ttysclp0 3270/tty1; do
		[ -e "/dev/$c" ] && echo "$c"
	done
)
have=$(s6-instance-list "$svc" 2>/dev/null)
r=0
for i in $(printf '%s\n' "$ttys" | tr / '!' | sort -u); do
	printf '%s\n' "$have" | grep -qxF "$i" && continue
	if s6-instance-create -t 5000 "$svc" "$i"; then
		echo "getty-generator: serial-getty@$i"
	else
		r=1
	fi
done
exit $r
