#!/bin/zsh
# Runs for interactive shells

export START="${START:=$(date '+%s.%N')}"

checkCommand(){
    type "$1" >/dev/null 2>&1
}
# If you have zellij installed, this will auto start it
#if [ -z "$ZELLIJ" ] && checkCommand zellij; then
#    #export ZELLIJ_AUTO_ATTACH=true
#    exec zellij
#fi

# Speed up shell load on WSL
OLDPATH=$PATH
PATH=$(echo "$PATH" | sed -e 's/\/mnt\/.*\?://g')


# Uncomment to debug lag
#zmodload zsh/zprof

# Set where history is saved and how much to save
HISTFILE="$XDG_STATE_HOME/zsh/history"
[ ! -e $HISTFILE ] && mkdir -p "$XDG_STATE_HOME/zsh" && touch $HISTFILE
HISTSIZE=10000
SAVEHIST=10000

# disable system beep on error
setopt BEEP
# if you type a folder name, it will automatically cd into it
setopt autocd 
# if a glob has no matches, display an error
setopt nomatch
# report status of bg jobs immediately
setopt notify 
#dedupe history, and append to histfile after every command
setopt histfindnodups histsavenodups incappendhistory 
# correct all arguments in a line
setopt correctall
# vim style line editing
bindkey -v
# make file name completion case-insensitive
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*' cache-path $XDG_CACHE_HOME/zsh/zcompcache

# Move completions to XDG Dir
autoload -Uz compinit
compinit -d "$XDG_CACHE_HOME"/zsh/zcompdump-"$ZSH_VERSION"


# Use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
HYPHEN_INSENSITIVE="true"

# Enable command auto-correction.
ENABLE_CORRECTION="true"

# Display red dots whilst waiting for completion.
COMPLETION_WAITING_DOTS="true"

# Speed up autosuggestions
ZSH_AUTOSUGGEST_MANUAL_REBIND="true"

# fix home end and delete buttons
# create a zkbd compatible hash;
# to add other keys to this hash, see: man 5 terminfo
typeset -g -A key

key[Home]="${terminfo[khome]}"
key[End]="${terminfo[kend]}"
key[Insert]="${terminfo[kich1]}"
key[Backspace]="${terminfo[kbs]}"
key[Delete]="${terminfo[kdch1]}"
key[Up]="${terminfo[kcuu1]}"
key[Down]="${terminfo[kcud1]}"
key[Left]="${terminfo[kcub1]}"
key[Right]="${terminfo[kcuf1]}"
key[PageUp]="${terminfo[kpp]}"
key[PageDown]="${terminfo[knp]}"
key[Shift-Tab]="${terminfo[kcbt]}"

# setup key accordingly
[[ -n "${key[Home]}"      ]] && bindkey -- "${key[Home]}"       beginning-of-line
[[ -n "${key[End]}"       ]] && bindkey -- "${key[End]}"        end-of-line
[[ -n "${key[Insert]}"    ]] && bindkey -- "${key[Insert]}"     overwrite-mode
[[ -n "${key[Backspace]}" ]] && bindkey -- "${key[Backspace]}"  backward-delete-char
[[ -n "${key[Delete]}"    ]] && bindkey -- "${key[Delete]}"     delete-char
[[ -n "${key[Up]}"        ]] && bindkey -- "${key[Up]}"         up-line-or-history
[[ -n "${key[Down]}"      ]] && bindkey -- "${key[Down]}"       down-line-or-history
[[ -n "${key[Left]}"      ]] && bindkey -- "${key[Left]}"       backward-char
[[ -n "${key[Right]}"     ]] && bindkey -- "${key[Right]}"      forward-char
[[ -n "${key[PageUp]}"    ]] && bindkey -- "${key[PageUp]}"     beginning-of-buffer-or-history
[[ -n "${key[PageDown]}"  ]] && bindkey -- "${key[PageDown]}"   end-of-buffer-or-history
[[ -n "${key[Shift-Tab]}" ]] && bindkey -- "${key[Shift-Tab]}"  reverse-menu-complete

# Finally, make sure the terminal is in application mode, when zle is
# active. Only then are the values from $terminfo valid.
if (( ${+terminfo[smkx]} && ${+terminfo[rmkx]} )); then
	autoload -Uz add-zle-hook-widget
	function zle_application_mode_start { echoti smkx }
	function zle_application_mode_stop { echoti rmkx }
	add-zle-hook-widget -Uz zle-line-init zle_application_mode_start
	add-zle-hook-widget -Uz zle-line-finish zle_application_mode_stop
fi
#bindkey "${terminfo[khome]}" beginning-of-line
#bindkey "${terminfo[kend]}" end-of-line
#bindkey "${terminfo[kdch1]}" delete-char

#if ! checkCommand gum && checkCommand go; then
#	# TODO
#fi


#Allows fuzzy-finding
if checkCommand fzf; then
    export FZF_BASE=$(which fzf)
else
    git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf;
    ~/.fzf/install --bin;
    mkdir -p ~/.local/bin;
    mv ~/.fzf/bin/* ~/.local/bin/;
    rm -rf ~/.fzf;
fi

#todo: install if not found
# Load plugins
mkdir -p ~/.config/sheldon
touch ~/.config/sheldon/plugins.toml
if checkCommand sheldon; then
    eval "$(sheldon -q source)";
elif checkCommand brew; then
    brew install sheldon;
elif checkCommand cargo; then
    cargo install sheldon
else
    curl --proto '=https' -fLsS https://rossmacarthur.github.io/install/crate.sh \
        | bash -s -- --repo rossmacarthur/sheldon --to ~/.local/bin
fi

#zplug "plugins/git", from:oh-my-zsh, lazy:on 
#zplug "plugins/vi-mode", from:oh-my-zsh
#zplug "plugins/adb", from:oh-my-zsh, lazy:on
#zplug "plugins/pip", from:oh-my-zsh, lazy:on


# set colors if pywal is installed
if checkCommand wal  && [ -z "$SSH_TTY" ]; then
    eval 'cat ~/.cache/wal/sequences &'
fi

# if ssh-agent isn't running, run it
if ! pgrep -u "$USER" '(ssh|gpg)-agent' >/dev/null; then
    if checkCommand gpg-agent; then
        gpg-agent --daemon --enable-ssh-support;
        unset SSH_AGENT_PID;
        export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-socket);
        export GPG_TTY=$(tty)
        gpg-connect-agent updatestartuptty /bye >/dev/null
    elif checkCommand ssh-agent; then
        ssh-agent > "$HOME/.ssh-agent.env";
    fi
fi
if [ ! -f "$SSH_AUTH_SOCK" ] && [ -f ~/.ssh-agent.env ]; then
    source "$HOME/.ssh-agent.env" >/dev/null
fi

[[ -f ~/.zsh_history ]] && touch ~/.zsh_history

# Set up mcfly if installed (lets you search through history easily with ctrl+r)
if checkCommand mcfly; then
    zsh-defer _evalcache mcfly init zsh
fi

# set up zoxide if installed (lets you jump through folders easily using the z and zi commands instead of cd)
if checkCommand zoxide; then
    zsh-defer _evalcache zoxide init zsh
fi

#if "$(checkCommand notify-send)"; then
#    notify-send() { wsl-notify-send.exe --category $WSL_DISTRO_NAME "${@}"; }
#fi


# Set up broot if installed (a nicer tree, probably has other cool stuff I haven't looked at yet)
[ -e "$HOME"/.config/broot/launcher/bash/br ] && zsh-defer -t 5 eval "$(broot --print-shell-function zsh)" 
# Set aliases
[ -f "$HOME/.aliasrc" ] && source "$HOME/.aliasrc" # >/dev/null 2>&1 &;

if checkCommand mirafetch; then
    RUST_BACKTRACE=1 mirafetch
fi
END="$(date '+%s.%N')"
PATH=$OLDPATH
printf "Startup Time: %.2fms\n" $((1000 * (END - START)))
# todo: install if not found
checkCommand starship && eval "$(starship init zsh)"
unset OLDPATH
unset START
unset END


