# ALSA sound support.
{ config, pkgs, ... }:

with pkgs.lib;

let

  inherit (pkgs) alsaUtils;

  soundState = "/var/lib/alsa/asound.state";

in

{

  ###### interface

  options = {

    sound = {

      enable = mkOption {
        default = true;
        description = ''
          Whether to enable ALSA sound.
        '';
        merge = mergeEnableOption;
      };

      enableOSSEmulation = mkOption {
        default = true;
        description = ''
          Whether to enable ALSA OSS emulation (with certain cards sound mixing may not work!).
        '';
      };

    };

  };


  ###### implementation

  config = mkIf config.sound.enable {

    environment.systemPackages = [ alsaUtils ];

    boot.kernelModules = optional config.sound.enableOSSEmulation "snd_pcm_oss";

    jobs.alsa =
      { description = "ALSA Volume Settings";

        startOn = "stopped udevtrigger";

        preStart =
          ''
            mkdir -m 0755 -p $(dirname ${soundState})

            # Try to restore the sound state.
            ${alsaUtils}/sbin/alsactl --ignore init || true
            ${alsaUtils}/sbin/alsactl --ignore -f ${soundState} restore || true
          '';

        postStop =
          ''
            # Save the sound state.
            ${alsaUtils}/sbin/alsactl --ignore -f ${soundState} store
          '';
      };

  };

}

# ALSA sound support.
{ config, pkgs, ... }:

with pkgs.lib;

let

  inherit (pkgs) alsaUtils;

  soundState = "/var/lib/alsa/asound.state";

in

{

  ###### interface

  options = {

    sound = {

      enable = mkOption {
        default = true;
        description = ''
          Whether to enable ALSA sound.
        '';
        merge = mergeEnableOption;
      };

      enableOSSEmulation = mkOption {
        default = true;
        description = ''
          Whether to enable ALSA OSS emulation (with certain cards sound mixing may not work!).
        '';
      };

    };

  };


  ###### implementation

  config = mkIf config.sound.enable {

    environment.systemPackages = [ alsaUtils ];

    # ALSA provides a udev rule for restoring volume settings.
    services.udev.packages = [ alsaUtils ];

    boot.kernelModules = optional config.sound.enableOSSEmulation "snd_pcm_oss";

    boot.systemd.services."alsa-store" =
      { description = "Store Sound Card State";
        wantedBy = [ "shutdown.target" ];
        before = [ "shutdown.target" ];
        unitConfig.DefaultDependencies = "no";
        serviceConfig.Type = "oneshot";
        serviceConfig.ExecStart = "${alsaUtils}/sbin/alsactl store --ignore";
      };
  };

}

Use udev to restore ALSA volume settings
Use udev to restore ALSA volume settings

Alsa-utils provides a udev rule to restore volume settings, so use
that instead of restoring them from a systemd service.  The
"alsa-store" service saves the settings on shutdown.
