{ config, pkgs, ... }:

# based on
# https://github.com/yurifrl/NixFiles/blob/3b36740fb4063574247d5741247fb1bdf92520d8/modules/programs/xboxdrv.nix#L11
# https://github.com/Lassulus/superconfig/blob/0ac6dfb43ece63b6b3132aa7b56aa3366c7ed95d/machines/xerxes/config.nix#L43

# transitive links:
# https://github.com/NixOS/nixpkgs/issues/25490
# https://www.reddit.com/r/RetroPie/comments/bi5bm4/psa_new_method_for_disabling_ertm_fix_controller/
# https://github.com/baracoder/nix/blob/master/configuration.nix
# https://www.reddit.com/r/NixOS/comments/a7g4oi/declaratively_setting_sysfs_properties/
# https://nixos.org/nixos/options.html#kernel.sysctl
# https://github.com/timor/timor-overlay/blob/d49783d2880b730cd67dbe6700ea2968f893b32e/modules/xbox360-wireless.nix
# https://github.com/phildenhoff/pd/blob/44025561b223df9901e4415650deae08b1077865/dotfiles/entertainment.nix

let

  configFile = pkgs.writeFile "xboxdrv.ini" ''
    [xboxdrv]
    silent = true
    device-name = "Xbox 360 Wireless Receiver"
    mimic-xpad = true
    deadzone = 4000
    [xboxdrv-daemon]
    dbus = disabled
  '';

in

{
  boot.blacklistedKernelModules = [ "xpad" ];

  environment.systemPackages = [ pkgs.xboxdrv ];

  #environment.etc."default/xboxdrv".text = ''
  systemd.services.xboxdrv = {
    inherit (pkgs.xboxdrv.meta) description;
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      ExecStart = ''
        ${pkgs.xboxdrv}/bin/xboxdrv --daemon --config ${configFile}
      '';
      Restart = "always";
      RestartSec = 3;
    };
  };
}
