{ config, lib, pkgs, ... }:

let cfg = config.sydnix.deertopia.servarr;
in {
  options.sydnix.deertopia.servarr = {
    enable = lib.mkEnableOption "Deertopia's *arr suite";
    peer = lib.mkOption {
      default = "us-den-wg-101";
      type = lib.types.str;
      description = ''
        The name of a Wireguard configuration file in
        modules/nixos/deertopia/mullvad/, without the .conf suffix.  Ideally, we
        would support multiple peers without rebuilding, but...
      '';
    };
  };

  imports = [
    ./servarr/jellyfin.nix
    ./servarr/lidarr.nix
    ./servarr/prowlarr.nix
    ./servarr/sabnzbd.nix
    ./servarr/sonarr.nix
    ./servarr/radarr.nix
    ./servarr/transmission.nix
    # ./servarr/slskd.nix
  ];

  config = lib.mkIf cfg.enable {
    sydnix.impermanence.directories = [
      # "All services support state management and all state that they manage is
      # located by default in /data/.state/nixarr/*"
      # See https://nixarr.com/nixos-options/
      config.nixarr.stateDir
    ];

    # Mount our NAS's 'media' share.
    fileSystems."/media" = {
      # DNS is seemingly unavailable to the mount service.
      device = "//192.168.68.62/media";
      mountPoint = "/media";
      fsType = "cifs";
      options = [
        "vers=2.0"
        "cred=/run/secrets/buffalo-nas-creds"
        # Wait for network availability before attempting mount.
        "_netdev"
        "uid=${config.util-nixarr.globals.libraryOwner.user}"
        "gid=${config.util-nixarr.globals.libraryOwner.group}"
        # Mysteriously, 0664 doesn't work…
        "dir_mode=0770"
        "file_mode=0770"
        "x-systemd.automount"
      ];
    };

    sydnix.sops.secrets.wireguard-mullvad-key = {};

    systemd.services."create-wireguard-config" = {
      script = ''
        wgConf="${config.nixarr.stateDir}/wg.conf"
        cp "/persist/dots/modules/nixos/deertopia/mullvad/${cfg.peer}.conf" \
          "$wgConf"
        ${pkgs.replace-secret}/bin/replace-secret \
          '{{WG_PRIVATE_KEY}}' \
          /run/secrets/wireguard-mullvad-key \
          "$wgConf"
        ${pkgs.gnused}/bin/sed -i -e 's/^DNS.*/DNS = 1.1.1.1/' "$wgConf"
        chmod 700 "$wgConf"
        chown root "$wgConf"
      '';
      requiredBy = [ "wg.service" ];
    };

    # systemd.services.test-mullvad-connection = {
    #   script = ''
    #     ${pkgs.curl}/bin/curl -s https://am.i.mullvad.net/connected >&2
    #     ${pkgs.curl}/bin/curl -s https://am.i.mullvad.net/connected 2>/dev/null
    #   '';
    #   vpnconfinement = {
    #     enable = true;
    #     vpnnamespace = "wg";
    #   };
    # };

    nixarr = {
      enable = true;
      # The default value is overly anti-FHS.
      stateDir = "/var/lib/nixarr";
      mediaDir = "/media";
      vpn = {
        enable = true;
        wgConf = "${config.nixarr.stateDir}/wg.conf";
      };
    };
  };
}

