{ pkgs, lib, ... }:

with lib;

let
  xbacklightCmd = "${pkgs.xorg.xbacklight}/bin/xbacklight";
  xsetCmd = "${pkgs.xorg.xset}/bin/xset";
  lightLevel = 10;

  saveLightLevel = pkgs.writeShellScript "saveLightLevel" ''
    ${xbacklightCmd} -get > /run/user/$UID/xbacklight_v
  '';
  lowerLight = pkgs.writeShellScript "lower_light" ''
    ${xbacklightCmd} -set ${toString lightLevel}
  '';
  resetLight = pkgs.writeShellScript "reset_light" ''
    ${xbacklightCmd} -set $(</run/user/$UID/xbacklight_v) || ${xbacklightCmd} -set 100
  '';
  shutDownScreens = pkgs.writeShellScript "shutdown_screens" ''
    ${xsetCmd} dpms force off
  '';
in
{
  services.xidlehook = {
    enable = true;
    package = pkgs.writeScriptBin "xidlehook" ''
      ${pkgs.xidlehook}/bin/xidlehook --detect-sleep "$@"
    '';
    # not-when-audio = true;
    not-when-fullscreen = true;
    timers = [
      {
        command = "${saveLightLevel} && ${lowerLight}";
        canceller = "${resetLight}";
        delay = 60;
      }
      {
        command = "${pkgs.lockscreen}/bin/lockscreen";
        canceller = "${resetLight}";
        delay = 120;
      }
      {
        command = "${shutDownScreens}";
        canceller = "${resetLight}";
        delay = 300;
      }
    ];
  };
}
