{ 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 () {
        nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [ $@ ])" \
          --run ghci
      }

      # Run GHC with the given packages made available.
      ghc-with-packages () {
        getopt -o "p" -- "$@"
        while true; do
          case "$1" in
            -p)
              packages="$1"
              shift 2
              ;;
            --)
              shift
              break
              ;;
          esac
        done

        if [ $? -ne 0 ]; then
         echo "Invalid options provided"
         exit 1
        fi

        eval set -- "$options"

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

    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")
      ];
  };
}

