#!/bin/sh
# Pick a ghq repo or an Obsidian vault with fzf (tab toggles the list);
# prints the directory for the shell wrapper to cd into.
vaults="$HOME/Documents/Obsidian/Personal $HOME/Documents/Obsidian/Walletbase $HOME/Documents/Obsidian/Research"

# chezmoi's source tree is a normal checkout of github.com/prdlk/dotfiles, but
# it lives under ~/.local/share, not ghq's root, so `ghq list` never sees it.
# List it under its GitHub name and translate that back to the real path below.
chezmoi_dir="$HOME/.local/share/chezmoi"
chezmoi_entry="github.com/prdlk/dotfiles"

# One command string, used both for the initial list and for fzf's reload
# binding, so the two can't drift.
repos="{ ghq list; [ -d $chezmoi_dir ] && echo $chezmoi_entry; } | sort"

# fzf runs bind actions with $SHELL -c; pin it to sh so the transform
# snippet below is interpreted consistently regardless of login shell.
selection=$(eval "$repos" | SHELL=/bin/sh fzf --prompt="repo: " --tiebreak=end \
    --bind "tab:transform:if [ \"\$FZF_PROMPT\" = 'repo: ' ]; then
            echo \"change-prompt(vault: )+reload(printf '%s\\n' $vaults)\"
        else
            echo 'change-prompt(repo: )+reload($repos)'
        fi") || exit 1
[ -n "$selection" ] || exit 1

# Vault entries are absolute paths; ghq entries are host/user/repo
case "$selection" in
    /*) printf '%s\n' "$selection" ;;
    "$chezmoi_entry") printf '%s\n' "$chezmoi_dir" ;;
    *) printf '%s\n' "$(ghq root)/$selection" ;;
esac
