### This configuration makes zsh fully "XDG compliant". One change is needed to
### /etc/zsh/zshenv (or equivalent upstream profile): 
###		`export ZDOTDIR="$HOME"/.config/zsh`
#
# Lines configured by zsh-newuser-install
export HISTFILE="$XDG_STATE_HOME"/zsh/history
mkdir -p "$(dirname "$HISTFILE")"
HISTSIZE=100000
SAVEHIST=100000
setopt autocd
unsetopt beep
bindkey -v
# End of lines configured by zsh-newuser-install
# The following lines were added by compinstall
zstyle :compinstall filename "$ZDOTDIR/.zshrc"

autoload -Uz compinit
compinit -d "$XDG_CACHE_HOME"/zsh/zcompdump-"$ZSH_VERSION"
# End of lines added by compinstall
### User configuration

# for shell integration
precmd() {
	print -Pn "\e]133;A\e\\"
}

# prompt configuration
autoload -Uz vcs_info
precmd_vcs_info () { vcs_info }
precmd_functions+=( precmd_vcs_info )
setopt prompt_subst
zstyle ':vcs_info:*' formats ' %F{green}%b'
PROMPT='%F{yellow}%n@%m %F{white}%1~%(?.. %?) $ '
RPROMPT='%f$vcs_info_msg_0_ '

# Detect if we're in a schroot and modify prompt accordingly
if [[ -n "$SCHROOT_CHROOT_NAME" ]]; then
    # We're in a schroot - add [chroot:name] to the prompt
    PS1="[chroot:$SCHROOT_CHROOT_NAME] $PS1"
fi

# share history between open shells
setopt share_history

alias boinctui='boinctui --boinchost=localhost'
alias bt='bluetoothctl'
alias c='clear'
alias daybreak='mosh daybreak -p 60101'
alias epoch='mosh epoch -p 60104'
alias grc='gridcoinresearchd'
alias l='eza -lh --all --octal-permissions'
alias less='less -r'
alias ls='eza'
alias lsa='eza -a'
alias lss='eza -a'
alias vim='nvim'
alias wake_circadian='ssh epoch wol a8:a1:59:11:06:f1'
alias xrm='sudo xbps-remove'
alias zf='z --pipe="fzf"'

if [[ -n "$WSL_DISTRO_NAME" ]]; then
    alias adb='adb.exe'
    alias choco='choco.exe'
    alias fastboot='fastboot.exe'
    alias gsudo='gsudo.exe'
    alias pwsh='pwsh.exe'
    alias usbipd='usbipd.exe'
fi

# GPG setup (and SSH)
# SSH setup
# I finally figured out how to export my id_rsa from GPG using
# https://superuser.com/a/1681454 (copied/summarized here to avoid link rot):
# 0. Run `gpg -K --with-keygrip` and note the desired keygrip (probably the one
#   with [A] for auth).
# 1. Run `gpgsm --gen-key -o tempcert`:
#   a. Select "Existing Key".
#   b. Enter the keygrip from step 0.
#   c. Select "(1) sign, encrypt". This and following steps don't really apply
#   for our use case, but we need to do it to make the tool happy.
#   d. Enter some valid X.509 subject, e.g. "C=US".
#   e. Press enter for rest of fields.
#   f. "y" to create self-signed certificate.
#   g. "y" to proceed with creation.
# 2. `gpgsm --import tempcert` and `gpgsm -K` to get the (new) keyid.
# 3. `gpgsm --export-secret-key-p8 -a -o id_rsa $keyid`
# 4. (optional) `rm tempcert`, probably don't want that sitting around.
# 5. (optional) Trim the phony metadata we gave to gpgsm that is prepended to
# the exported PEM cert (id_rsa).
if command -v keychain >/dev/null; then
	alias keychain="keychain --nolock --absolute --dir $XDG_RUNTIME_DIR"
	eval "$(keychain --quick --eval)"
  if command -v rbw >/dev/null; then
    rbw unlock
    SSH_ASKPASS=get_id_rsa_pass SSH_ASKPASS_REQUIRE=force ssh-add ~/.ssh/id_rsa
  else
    ssh-add ~/.ssh/id_rsa
  fi
fi

# Command not found handler
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
    function command_not_found_handler {
        if [ -x /usr/lib/command-not-found ]; then
            /usr/lib/command-not-found -- "$1"
            return $?
        elif [ -x /usr/share/command-not-found/command-not-found ]; then
            /usr/share/command-not-found/command-not-found -- "$1"
            return $?
        else
            printf "zsh: command not found: %s\n" "$1" >&2
            return 127
        fi
    }
fi

### hooks/includes
for plugin in zsh-syntax-highlighting zsh-history-substring-search zsh-autosuggestions; do
    # Define possible locations for this plugin
    possible_locations=(
        # Standard location
        "/usr/share/zsh/plugins/$plugin/$plugin.zsh"
        # Nix
        "/nix/var/nix/profiles/default/share/$plugin/$plugin.zsh"
        # Direct in /usr/share
        "/usr/share/$plugin/$plugin.zsh"
        # Home directory locations
        "$HOME/.local/share/$plugin/$plugin.zsh"
        # Version-specific directory (for history-substring-search)
        "$HOME/.local/share/$plugin/$plugin-*/($plugin).zsh"
        # Oh-My-Zsh style plugin location
        "$HOME/.oh-my-zsh/custom/plugins/$plugin/$plugin.zsh"
        # Homebrew location (for macOS users)
        "/usr/local/share/$plugin/$plugin.zsh"
    )
    # Try each location until we find one that exists
    for location in "${possible_locations[@]}"; do
        # Expand the path in case it contains wildcards
        expanded_locations=( ${~location} )
        # Check each expanded location
        for expanded_location in "${expanded_locations[@]}"; do
            if [[ -f "$expanded_location" ]]; then
                source "$expanded_location"
                # Break out of the inner loop
                break 2
            fi
        done
    done
done

bindkey '^[[A' history-substring-search-up
bindkey '^[[B' history-substring-search-down
bindkey -M vicmd 'k' history-substring-search-up
bindkey -M vicmd 'j' history-substring-search-down

if command -v pazi &>/dev/null; then
  eval "$(pazi init zsh)" # or 'bash'
fi

### End user configuration
