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

{
  # Enable the auto-cpufreq daemon
  services.auto-cpufreq.enable = true;

  # Enable the TLP daemon
  services.tlp = {
    enable = true;
    settings = {
      # Enable audio power saving for Intel HDA, AC97 devices (timeout in secs).
      # A value of 0 disables, >=1 enables power saving (recommended: 1).
      # Default: 0 (AC), 1 (BAT)
      SOUND_POWER_SAVE_ON_AC = 0;
      SOUND_POWER_SAVE_ON_BAT = 1;

      # Runtime Power Management for PCI(e) bus devices: on=disable, auto=enable.
      # Default: on (AC), auto (BAT)
      RUNTIME_PM_ON_AC = "on";
      RUNTIME_PM_ON_BAT = "auto";

      # Battery feature drivers: 0=disable, 1=enable
      # Default: 1 (all)
      NATACPI_ENABLE = 1;
      TPACPI_ENABLE = 1;
      TPSMAPI_ENABLE = 1;
    };
  };

  # Suspend when the battery is critical
  services.udev.extraRules = ''
    SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{model_name}=="01AV405", ATTR{capacity}=="[0-5]", RUN+="${config.systemd.package}/bin/systemctl suspend -i"
  '';

  # Enable thinkfan
  services.thinkfan = {
    enable = true;
    levels = [
      [ 0 0 47 ]
      [ 1 47 69 ]
      [ 2 69 74 ]
      [ 3 74 78 ]
      [ 4 78 82 ]
      [ 5 82 85 ]
      [ 6 85 87 ]
      [ 7 87 32767 ]
    ];
  };
  # HACK Workaround to enable the service the first time
  systemd.services.thinkfan.preStart = ''
    /run/current-system/sw/bin/modprobe  -r thinkpad_acpi && /run/current-system/sw/bin/modprobe thinkpad_acpi
  '';
}