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

let
  inherit (pkgs.lib) optionalAttrs;

  home-manager = "${pkgs.home-manager}/bin/home-manager";
  grep = lib.getExe' pkgs.toybox "grep";
  head = lib.getExe' pkgs.toybox "head";
  find = lib.getExe' pkgs.toybox "find";

  find-generation = ''
    for line in $(${home-manager} generations | ${grep} -o '/.*')
    do
      res=$(${find} $line | ${grep} specialisation | ${head} -1)
      output=$?

      if [[ $output -eq 0 ]] && [[ $res != "" ]]; then
        echo $res
        exit
      fi
    done
  '';

  switch-theme = theme: "$(${find-generation})/${theme}/activate && systemctl restart --user hyprpaper";
in
{
  options.modules.darkman = {
    enable = lib.mkEnableOption "Darkman service and integration";
    customLightModeScript = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "Path to custom light mode script";
    };

    customDarkModeScript = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
      description = "Path to custom dark mode script";
    };
  };

  config = lib.mkIf config.modules.darkman.enable {
    services.darkman = {
      enable = true;
      darkModeScripts =
        optionalAttrs (config.modules.darkman.customDarkModeScript != null) {
          custom = config.modules.darkman.customDarkModeScript;
        }
        // optionalAttrs (config.modules.stylix.enable) {
          stylix = switch-theme "dark";
        };

      lightModeScripts =
        optionalAttrs (config.modules.darkman.customLightModeScript != null) {
          custom = config.modules.darkman.customLightModeScript;
        }
        // optionalAttrs (config.modules.stylix.enable) {
          stylix = switch-theme "light";
        };

      settings.usegeoclue = true;
    };
  };
}
