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

with lib;

let

  cfg = config.programs.jump;

  enabled = cfg.enableBash || cfg.enableZsh;

in {
  meta.maintainers = [ hm.maintainers.pbsds ];

  options.programs.jump = {
    # Jumping around with symbolic links
    # Based on http://jeroenjanssens.com/2013/08/16/quickly-navigate-your-filesystem-from-the-command-line.html

    enableBash = mkEnableOption "jump - Quickly Navigate your Filesystem";
    enableZsh = mkEnableOption "jump - Quickly Navigate your Filesystem";

    marksPath = mkOption {
      type = types.str;
      default = "$HOME/.marks";
      description = ''
        Where the jump marks are stored
      '';
    };

  };

  config = mkIf enabled {
    #home.packages = [ cfg.package ];

    home.sessionVariables = { _JUMP_MARKPATH = cfg.marksPath; };

    programs = let
      rcScript = ''
        function _mark_choose() {
            ${lib.getExe pkgs.fd} . "$_JUMP_MARKPATH" --type l -X ${lib.getExe pkgs.gum} choose --ordered {/}
        }
        function jump() {
          local target="''${1:-$(_mark_choose)}"
          if test -n "$target"; then
            pushd . > /dev/null
            cd -P "$_JUMP_MARKPATH/$target" 2>/dev/null || echo "No such mark: $target"
          fi
        }
        function mark() {
          mkdir -p "$_JUMP_MARKPATH" &&
          test ! -L "$_JUMP_MARKPATH/$1" \
              && ln -s "$(pwd)" "$_JUMP_MARKPATH/$1" \
              || echo "mark already exists!"
        }
        function unmark() {
            local target="''${1:-$(_mark_choose)}"
            if test -n "$target"; then
              rm -i "$_JUMP_MARKPATH/$target"
            fi
        }
        function marks() {
          #ls -l "$_JUMP_MARKPATH" | sed 's/  / /g' | cut -d' ' -f9- | sed 's/ -/\t-/g' && echo
          command ls --color=always -l "$_JUMP_MARKPATH" | tr -s ' ' | cut -d' ' -f9- | sed -e 's/ -> /§/g' | column -t -s '§' -o ' -> '
        }
        _complete_jump_marks() {
          local curw=''${COMP_WORDS[COMP_CWORD]}
          local wordlist=($(find "$_JUMP_MARKPATH" -type l -printf "%f\n"))
          COMPREPLY=($(compgen -W "''${wordlist[@]}" -- "$curw"))
          return 0
        }
        complete -F _complete_jump_marks jump unmark
      '';
    in {
      # TODO: fish
      bash.initExtra = mkIf cfg.enableBash rcScript;
      zsh.initExtra = mkIf cfg.enableZsh rcScript;
    };

  };
}
