#!/bin/sh
# Wait for hostname + udev before agetty. If elogind is installed, also wait
# so startx gets a seat (uaccess); skip that wait when elogind is absent.
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH

TIMEOUT=${EARLY_GETTY_WAIT:-120}
i=0
have_hostname=0
have_udev=0
have_elogind=0
want_elogind=0

if [ -f /etc/s6-rc/sv/elogind/type ] || [ -x /usr/libexec/elogind ] || \
   [ -x /usr/lib/elogind/elogind ]; then
	want_elogind=1
else
	have_elogind=1
fi

while [ "$i" -lt "$TIMEOUT" ]; do
	if [ "$have_hostname" -eq 0 ]; then
		if command -v s6-rc >/dev/null 2>&1 && \
		   s6-rc -a list 2>/dev/null | grep -qx hostname; then
			have_hostname=1
		else
			hn=$(hostname 2>/dev/null || cat /proc/sys/kernel/hostname 2>/dev/null || true)
			hn=$(printf '%s' "$hn" | tr -d ' \t\r\n')
			case "$hn" in ""|"(none)") ;; *) have_hostname=1 ;; esac
		fi
	fi
	if [ "$have_udev" -eq 0 ]; then
		if command -v s6-rc >/dev/null 2>&1 && \
		   s6-rc -a list 2>/dev/null | grep -qx udevadm; then
			have_udev=1
		elif udevadm control --ping >/dev/null 2>&1; then
			have_udev=1
		fi
	fi
	if [ "$want_elogind" -eq 1 ] && [ "$have_elogind" -eq 0 ]; then
		if command -v s6-rc >/dev/null 2>&1 && \
		   s6-rc -a list 2>/dev/null | grep -qx elogind; then
			have_elogind=1
		elif dbus-send --system --print-reply --dest=org.freedesktop.login1 \
			/org/freedesktop/login1 org.freedesktop.DBus.Peer.Ping \
			>/dev/null 2>&1; then
			have_elogind=1
		fi
	fi
	if [ "$have_hostname" -eq 1 ] && [ "$have_udev" -eq 1 ] && \
	   [ "$have_elogind" -eq 1 ]; then
		break
	fi
	sleep 1
	i=$((i + 1))
done

if [ "$want_elogind" -eq 1 ]; then
	udevadm trigger --action=add --subsystem-match=input >/dev/null 2>&1 || true
	udevadm settle --timeout=10 >/dev/null 2>&1 || true
fi

exec /sbin/agetty -L -8 tty1 115200
