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

let
  cfg = config.sydnix.users.crumb.haskell;
in {
  options.sydnix.users.crumb.haskell.enable =
    lib.mkEnableOption "Haskell, à la crumb";

  config = lib.mkIf cfg.enable {
    # Convenient shorthand for quickly opening Haskell REPLs.
    programs.bash.profileExtra = ''
      # Start a GHCi REPL with the given packages made available.
      ghci-with-packages () {
        packages=""
        while getopts 'p:h' opt; do
          case "$opt" in
            p)
              packages="''${OPTARG}"
              ;;
            ?|h)
              echo >&2 "Usage: $(basename $0) [-p packages] [-- ghci-options]"
              exit 1
              ;;
          esac
        done
        shift "$(($OPTIND -1))"

        nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [ $packages ])" \
          --run "ghci $@"
      }
      export -f ghci-with-packages

      # Run GHC with the given packages made available.
      ghc-with-packages () {
        packages=""
        while getopts 'p:h' opt; do
          case "$opt" in
            p)
              packages="''${OPTARG}"
              ;;
            ?|h)
              echo >&2 "Usage: $(basename $0) [-p packages] [-- ghc-options]"
              exit 1
              ;;
          esac
        done
        shift "$(($OPTIND -1))"

        nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [ $packages ])" \
          --run "ghc $@"
      }
      export -f ghc-with-packages
    '';

    sydnix.impermanence.cache.directories =
      let xdg-cache-dir =
            config.home.cacheHome
              or "${config.home.homeDirectory}/.cache";
      in [
        # We don't want to rebuild Hackage simply due to a reboot, do we?  }:)
        (lib.removePrefix "${config.home.homeDirectory}/"
          "${xdg-cache-dir}/cabal")
        ".stack"
      ];
  };
}

