#!/bin/sh
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/rescue

# shellcheck source=runit/functions
. /usr/local/etc/runit/functions
detect_jail

if [ -e /var/run/runit/reboot ]; then
	chmod 100 /var/run/runit/reboot
fi

reset -Q
echo "=> Waiting for services to stop"
sv force-stop /var/service/*
sv exit /var/service/*

[ -x /usr/local/etc/runit/local.shutdown ] && /usr/local/etc/runit/local.shutdown
/usr/sbin/utx shutdown

if [ -r /dev/mixer0 ]; then
	echo "=> Saving soundcard mixer values"
	for dev in /dev/mixer*; do
		if [ -r "${dev}" ]; then
			/usr/sbin/mixer -f "${dev}" -s >"/var/db/${dev##*/}-state" 2>/dev/null
		fi
	done
fi

[ -n "${JAILED}" ] && return 0
# Write some entropy so when the machine reboots /dev/random
# can be reseeded
echo "=> Writing entropy file"
rm -f /entropy 2>/dev/null
oumask=$(umask)
umask 077
if touch /entropy 2>/dev/null; then
	entropy_file_confirmed=/entropy
else
	# Try this as a reasonable alternative for read-only
	# roots, diskless workstations, etc.
	rm -f /var/db/entropy-file 2>/dev/null
	if touch /var/db/entropy-file 2>/dev/null; then
		entropy_file_confirmed=/var/db/entropy-file
	fi
fi
case ${entropy_file_confirmed} in
'')
	echo "WARNING: write failed (read-only fs?)"
	;;
*)
	dd if=/dev/random of=${entropy_file_confirmed} \
		bs=4096 count=1 2>/dev/null ||
		echo "WARNING: write failed (unwriteable file or full fs?)"
	;;
esac
umask "${oumask}"

echo "=> Writing early boot entropy file"
rm -f /boot/entropy 2>/dev/null
oumask=$(umask)
umask 077
if touch /boot/entropy 2>/dev/null; then
	entropy_boot_file_confirmed=/boot/entropy
fi
case ${entropy_boot_file_confirmed} in
'')
	echo "WARNING: write failed (read-only fs?)"
	;;
*)
	dd if=/dev/random of=${entropy_boot_file_confirmed} \
		bs=4096 count=1 2>/dev/null ||
		echo "WARNING: write failed (unwriteable file or full fs?)"
	;;
esac
umask "${oumask}"
