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

with lib;
let
  cfg = config.my.programs.bspwm;
in
{
  options.my.programs.bspwm.enable = mkEnableOption "true";

  config = lib.mkIf cfg.enable {
    services = {
      xserver = {
        enable = true;
        layout = "de";
        displayManager = {
          defaultSession = "none+bspwm";
          autoLogin = {
            enable = true;
            user = "moritz";
          };
          lightdm.enable = true;
        };
        windowManager.bspwm.enable = true;
      };
    };

    home-manager.users.moritz = {
      xsession.windowManager.bspwm = {
        enable = true;
        rules = {
          "Zathura".state = "tiled";
          "Emacs".state = "tiled";
          "feh".state = "floating";
          "Vampire_Survivors".state = "fullscreen";
        };
        settings = {
          border_width = 2;
          window_gap = 5;
          borderless_monocle = true;
          gapless_monocle = true;
          focus_follows_pointer = true;
        };
        startupPrograms = [
          "randomWallpaper"
          "${pkgs.synology-drive-client}/bin/synology-drive"
        ];
        extraConfig = builtins.readFile ./bspwmrc;
      };
      services = {
        unclutter.enable = true;
        sxhkd = {
          enable = true;
          extraConfig = builtins.readFile ./sxhkdrc;
        };
        polybar = {
          enable = true;
          package = pkgs.polybar.override { pulseSupport = true; };
          script = ''
            for m in $(polybar --list-monitors | ${pkgs.coreutils}/bin/cut -d":" -f1); do
                MONITOR=$m polybar --reload bottom &
            done
          '';
        };
      };
      systemd.user.targets.tray = {
        Unit = {
          Description = "Bspwm Tray Target";
          After = [ "graphical-session.target" ];
        };
        Install = {
          WantedBy = [ "graphical-session.target" ];
        };
      };
    };

    programs.xss-lock = {
      enable = true;
      lockerCommand = "${pkgs.i3lock-fancy-rapid}/bin/i3lock-fancy-rapid 10 5";
    };

    environment.systemPackages = with pkgs; [
      bc # HACK to get bsp-layout to work
      brightnessctl
      bsp-layout
      feh
      pamixer
      playerctl
      synology-drive-client
    ];
  };
}
