#!/usr/bin/execlineb -P
# Restore ALSA levels. Soft-fail if no cards yet.
# Prefer cards after vdev coldplug; soft-wait briefly if none yet (~5s).
foreground {
	pipeline { seq 50 }
	forstdin -x 1 i
	ifelse { test -d /proc/asound }
	{ exit 1 }
	sleep 0.1
}

# With vdev: load PCI audio drivers (class 0x0401* / 0x0403*) before restore.
if { test -x /usr/sbin/vdevd }
foreground {
	elglob -0 devices /sys/bus/pci/devices/*
	forx -E path { $devices }
	ifelse { test -f ${path}/class }
	{
		backtick -n class { cat ${path}/class }
		importas -uS class
		ifelse {
			pipeline { printf "%s\n" $class }
			grep -qE "^0x040[13]"
		}
		{
			backtick -n modalias { cat ${path}/modalias }
			importas -uS modalias
			foreground { /sbin/modprobe -b -q -- $modalias }
			exit 0
		}
		exit 0
	}
	exit 0
}

# Cards may still be absent briefly; do not fail the boot.
ifelse -n { test -d /proc/asound }
{
	foreground {
		fdmove -c 1 2
		echo no sound cards loaded yet
	}
	exit 0
}

ifelse { test -x /usr/sbin/alsactl }
{
	foreground { install -d -m 755 /run/alsa/runtime }
	ifelse -n { test -e /var/lib/alsa/asound.state } { exit 0 }
	export HOME /run/alsa
	export XDG_RUNTIME_DIR /run/alsa/runtime
	foreground {
		redirfd -w 1 /dev/null
		redirfd -w 2 /dev/null
		/usr/sbin/alsactl -F restore
	}
	exit 0
}

ifelse -n { test -x /sbin/alsactl } { exit 0 }
foreground { install -d -m 755 /run/alsa/runtime }
ifelse -n { test -e /var/lib/alsa/asound.state } { exit 0 }
export HOME /run/alsa
export XDG_RUNTIME_DIR /run/alsa/runtime
foreground {
	redirfd -w 1 /dev/null
	redirfd -w 2 /dev/null
	/sbin/alsactl -F restore
}
exit 0
