# ZSH-specific environment variables
# Override in .profile.local

## oh-my-zsh
# Automatically update oh-my-zsh without asking
DISABLE_UPDATE_PROMPT=true
# Disable oh-my-zsh auto-update checks
DISABLE_AUTO_UPDATE=false
# How often to check for oh-my-zsh updates
UPDATE_ZSH_DAYS=30
# Disable cowsay on login by default.
NO_ZSHRC_COWSAY=1
# Theme to load [~/.oh-my-zsh/themes/]
ZSH_THEME="agnoster"
# Automatic window title setting
DISABLE_AUTO_TITLE="true"
# Command correction support
ENABLE_CORRECTION="false"
# Case-sensitive completion
CASE_SENSITIVE="false"
# ls colors
DISABLE_LS_COLORS="false"
# Red ... on completion waiting
COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
#
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"

# User profiles
source $HOME/.profile
# Define $POWERLINE_ROOT
if [ -f $HOME/.profile.local ]; then
    set -a
    source $HOME/.profile.local
    set +a
fi

# Custom functions
source "$HOME/.zsh_functions"

if [ -n "$DOTFILES_DIR" ] && [ -d "$DOTFILES_DIR" ]; then
    # Load dependencies
    ## oh-my-zsh
    if [ ! -f "$DOTFILES_DIR/dependencies/ohmyzsh/oh-my-zsh.sh" ]; then
        cd "$DOTFILES_DIR"
        git submodule update --init
        cd -
    fi
    export ZSH=$DOTFILES_DIR/dependencies/ohmyzsh
    ## Gruvbox colors
    [[ -f "$DOTFILES_DIR/dependencies/gruvbox/gruvbox_256palette.sh" ]] && source "$DOTFILES_DIR/dependencies/gruvbox/gruvbox_256palette.sh"
fi
missing_dependencies=()
for dependency in "${dependencies[@]}"; do
    if ! program_installed $dependency; then
        missing_dependencies+="$dependency"
    fi
done
if [ "${#missing_dependencies[@]}" -gt 0 ]; then
    echo "Missing dependencies: ${missing_dependencies[@]}"
fi

# Dircolors
# eval $(dircolors ~/.dircolors)

# tmux
zmodload zsh/zpty

# Enable environment variables as CD directories
setopt cdablevars
# Enable correction for mistyped commands
unsetopt correctall
setopt appendhistory autocd extendedglob
unsetopt beep

alias -s txt=vim
alias -s .c=vim

if [ -d $ZSH ] && [ ! -z $ZSH ]; then
    source $ZSH/oh-my-zsh.sh
fi

# Italic support
if [ -f $HOME/.xterm-256color-italic.terminfo ]; then
    tic $HOME/.xterm-256color-italic.terminfo
fi
if [ -f $HOME/.screen-256color-italic.terminfo ]; then
    tic $HOME/.screen-256color-italic.terminfo
fi

# TODO: Remove this
# Use neovim where available
# if type nvim > /dev/null 2>&1; then
#     alias vim='nvim'
# fi

# # Preferred editor for local and remote sessions
# # if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# export TERM=xterm-256color
# TODO ====

bindkey -v

# Keybindings
bindkey -M vicmd 'K' run-help
bindkey -M viins ',,' vi-cmd-mode
# bindkey -M viins 'K' run-help

# This binds Ctrl-O to ranger-cd:
#zle -N ranger-cd
#bindkey '^o' ranger-cd
#zle -N terminal-clock
#bindkey '^t' terminal-clock
# TMuxinator Completion
# source ~/bin/tmuxinator.zsh

zstyle :compinstall filename '~/.zshrc'
autoload -Uz compinit
compinit

DEFAULT_USER="$USER"

# Syntax highlighting configuration
# ZSH_HIGHLIGHT_STYLES[path]='bold'
# ZSH_HIGHLIGHT_STYLES[path_prefix]=none
# ZSH_HIGHLIGHT_STYLES[path_approx]='fg=yellow'
# ZSH_HIGHLIGHT_STYLES[globbing]='fg=yellow'

# Source files
#typeset -ga sources
#sources+=$DOTFILES_DIR/shortcuts.txt

# Check dotfiles version
if [ -n "$NO_GIT_CHECK" ] && [ ! "$NO_GIT_CHECK" -eq 1 ]; then
    # 5 second timeout to avoid delaying
    timeout -k 5 5s $(which zsh) -c 'source ~/.zsh_functions && check_dotfiles_version'
    dotfiles_version=$?
    if [[ $dotfiles_version = 1 ]]; then
        echo "Dotfiles repository not present at $DOTFILES_DIR"
    elif [[ $dotfiles_version = 2 ]]; then
        echo "Dotfiles repository at $DOTFILES_DIR is outdated"
    elif [[ $dotfiles_version = 3 ]]; then
        echo "Dotfiles repository at $DOTFILES_DIR is ahead of origin"
    elif [[ $dotfiles_version = 4 ]]; then
        echo "Dotfiles repository at $DOTFILES_DIR has diverged from origin"
    elif [[ $dotfiles_version = 5 ]]; then
        echo "Dotfiles repository not set in $HOME/.dotfiles-config"
        echo "Please run ./install.sh in dotfiles repository and exit to create ~/.dotfiles-config"
        echo "The following will not work until this is set:"
        echo "  - oh-my-zsh will not be started"
        echo "  - gruvbox color palette will not be loaded"
        echo ""
    fi
fi

# Powerline
if program_installed powerline; then
    if [ -n "$POWERLINE_ROOT" ] && \
        [ -f "$POWERLINE_ROOT" ] && \
        [ -f "$POWERLINE_ROOT/bindings/zsh/powerline.zsh" ]; then
        # Skip lookup if location is known
        source "$POWERLINE_ROOT/bindings/zsh/powerline.zsh"
    else
        found=0
        set_powerline_zsh_sources
        for file in $POWERLINE_ZSH_SOURCES; do
            if [[ -a $file ]]; then
                # TODO: Store the POWERLINE_ROOT in .profile.local if found
                source $file
                found=1
                break
            fi
        done
        if [ $found -eq 0 ]; then
            echo "Powerline binding not found.\nPlease set \$POWERLINE_ROOT in .profile.local"
        fi
    fi
fi

# Tool options
export SHELLCHECK_OPTS="-e SC2029 -e SC2155"

# Limit claude-code: cap CPU/memory/process count
# Adjust the -p values if these limits are ever too tight.
# if program_installed claude && program_installed systemd-run; then
#     claude() {
#         systemd-run --user --scope --quiet \
#             -p CPUQuota=50% \
#             -p MemoryMax=6G \
#             -p TasksMax=512 \
#             -- command claude "$@"
#     }
# fi

# Syntax highlighting
if [ -f /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh ]; then
    source /usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh 
fi

# fzf fuzzy finder
if program_installed fzf; then
    # TODO: This is broken on debian fzf (no --zsh)
    source <(fzf --zsh)
fi

# thefuck command correction
if program_installed fuck; then
    eval "$(thefuck --alias)"
fi

# pyenv-virtualenv (for managing virtualenvs for different python versions)
if program_installed pyenv; then
    export PYENV_ROOT="$HOME/.pyenv"
    export PYENV_VIRTUALENV_DISABLE_PROMPT=1
    [[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
    eval "$(pyenv init - zsh)"
    # eval "$(pyenv virtualenv-init -)"
fi

# oh-my-zsh plugins (must come after all initialization above)
plugins=(archlinux colored-man-pages colorize command-not-found cp docker docker-compose fzf git history history-substring-search nmap npm pip poetry pyenv macos rsync snap ssh sudo systemd terraform thefuck tmux tmuxinator vi-mode virtualenv yarn zsh-interactive-cd zsh-navigation-tools)

# Local overrides
if [ -f $HOME/.zshrc_local ]; then
    source $HOME/.zshrc_local
fi

# Fun stupid opt-in stuff on new shell. Enable these in .profile.local
if program_installed neofetch; then
    if [ ! -n "$NO_NEOFETCH" ] || [ "$NO_NEOFETCH" -eq 1 ]; then 
    else
        neofetch
    fi
fi
if [ -n "$NO_ZSHRC_COWSAY" ] && [ ! "$NO_ZSHRC_COWSAY" -eq 1 ]; then
    # Make a random (cow?) with a random face say something
    fortune -a | fmt -80 -s | cowthink -$(shuf -n 1 -e b d g p s t w y)  -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n
fi
