{ config, pkgs, ... }:
let
    httpStreamPort = 8000;
in
{
    services.mpd = {
        enable = true;
        musicDirectory = "/data/music/flac";
        playlistDirectory = "/data/music/playlists";
        network.listenAddress = "any";
        extraConfig = ''
            audio_output {
                type "pulse"
                name "Local Music Player Daemon"
                server "127.0.0.1"
                mixer_type "software"
            }

            audio_output {
                type "fifo"
                name "fft"
                path "/tmp/mpd.fifo"
                format "44100:16:2"
            }

            audio_output {
                type            "httpd"
                name            "HTTP-Stream (Port 8000)"
                encoder         "vorbis"      # optional
                bind_to_address "0.0.0.0"
                port            "${toString httpStreamPort}"
                # quality       "5.0"           # do not define if bitrate is defined
                bitrate         "128"            # do not define if quality is defined
                format          "48000:16:1"
                always_on       "yes"           # prevent MPD from disconnecting all listeners when playback is stopped.
                tags            "yes"           # httpd supports sending tags to listening streams.
            }
        '';
    };

    hardware.pulseaudio = {
        enable = true;
        systemWide = true;
        tcp.enable = true;
        tcp.anonymousClients.allowedIpRanges = [ "127.0.0.1" ];
    };

    users.extraGroups.pulse-access = {
        members = [ "mpd" ];
    };
    # users.extraGroups.music = {
    #     members = [ "mpd" ];
    # };

    # Workaround https://github.com/NixOS/nixpkgs/issues/114399
    system.activationScripts.fix-pulse-permissions = ''
        chmod 755 /run/pulse
    '';

    environment.systemPackages = with pkgs; [ mpc-cli ];

    networking.firewall.allowedTCPPorts = [ config.services.mpd.network.port httpStreamPort ];
}
