[Main]
Type = oneshot
Version = 0.1.0
Description = "Restore and store ALSA mixer levels"
User = ( root )
Depends = ( devmanager mount-rw )
Options = ( !log )

[Start]
Execute = (
	# 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
)

[Stop]
Execute = (
	# Store ALSA levels.
	# Do not use bare backtick: it needs a command after the block.
	ifelse { test -x /usr/sbin/alsactl } {
		foreground { install -d -m 755 /run/alsa/runtime }
		ifelse -n { test -d /proc/asound } { 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 store
		}
		exit 0
	}
	ifelse -n { test -x /sbin/alsactl } { exit 0 }
	foreground { install -d -m 755 /run/alsa/runtime }
	ifelse -n { test -d /proc/asound } { 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 store
	}
	exit 0
)
