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

let 
  cfg = config.samfelag.modules.desktop.polybar;
  polybar_pkg = pkgs.polybar.override {
    i3Support = true;
    pulseSupport = true;
  };
  script = ''
    polybar top &
    polybar bottom &
  '';
in {

  options.samfelag.modules.desktop.polybar = {
    enable = lib.mkEnableOption "polybar";
  };

  config = lib.mkIf cfg.enable {

    # - Configuration ----------------------------

    home.packages = [
      polybar_pkg
    ];

    xdg.configFile."polybar/config.ini".source = ../../../config/.config/polybar/config.ini;
    xdg.configFile."polybar/bars".source = ../../../config/.config/polybar/bars;
    xdg.configFile."polybar/scripts".source = ../../../config/.config/polybar/scripts;

    systemd.user.services.polybar = {
      Unit = {
        Description = "Polybar status bar";
        PartOf = [ "tray.target" ];
        X-Restart-Triggers = [ "${config.xdg.configFile."polybar/config.ini".source}" ];
      };

      Service = {
        Type = "forking";
        PassEnvironment = "PATH";
        ExecStart =
          let scriptPkg = pkgs.writeShellScriptBin "polybar-start" script;
          in "${scriptPkg}/bin/polybar-start";
        Restart = "on-failure";
      };

      Install = { WantedBy = [ "tray.target" ]; };
    };
  };
}
