local_install_dir="$HOME/.local/install"

# =============================================================================
# Wayland Configuration
# =============================================================================

# Ensure that my shell context works with xwayland-satellite
export DISPLAY=":0"

# =============================================================================
# History configuration.
# =============================================================================
alias history='history -t "%Y-%m-%d"'

export HISTFILE="$HOME/.zsh_history"
export HISTSIZE=25000
export SAVEHIST=$HISTSIZE
export HISTORY_IGNORE="(ls|cd|pwd|exit)*"

setopt EXTENDED_HISTORY      # Write the history file in the ':start:elapsed;command' format.
setopt INC_APPEND_HISTORY    # Write to the history file immediately, not when the shell exits.
setopt SHARE_HISTORY         # Share history between all sessions.
setopt HIST_IGNORE_DUPS      # Do not record an event that was just recorded again.
setopt HIST_IGNORE_ALL_DUPS  # Delete an old recorded event if a new event is a duplicate.
setopt HIST_IGNORE_SPACE     # Do not record an event starting with a space.
setopt HIST_SAVE_NO_DUPS     # Do not write a duplicate event to the history file.
setopt HIST_VERIFY           # Do not execute immediately upon history expansion.
setopt APPEND_HISTORY        # append to history file (Default)
setopt HIST_NO_STORE         # Don't store history commands
setopt HIST_REDUCE_BLANKS    # Remove superfluous blanks from each command line being added to the history.
setopt INTERACTIVE_COMMENTS  # Allow comments in interactive shell.

export FZF_CTRL_R_OPTS="
  --preview 'echo {}' --preview-window up:3:hidden:wrap
  --bind 'ctrl-/:toggle-preview'
  --bind 'ctrl-y:execute-silent(echo -n {2..} | wl-copy)+abort'
  --color header:italic
  --header 'Press CTRL-Y to copy command into clipboard'"

# Enable ZSH Completion
autoload -Uz compinit && compinit

# =============================================================================
# Allow for menu-style tab completion.
# =============================================================================
zstyle ':completion:*' menu select

# =============================================================================
# GPG Initialization (Ensure prompts work properly).
# =============================================================================
export GPG_TTY=$(tty)

# =============================================================================
# Personalized Logging for Shell Setup
# =============================================================================
logging_enabled=false
log_dir="$HOME/.local/log/$USER"
log_file="$log_dir/shell.log"

if [ -d "$log_dir" ]; then
    export SHELL_LOG_FILE="$log_file"
    logging_enabled=true
    touch "$SHELL_LOG_FILE"
fi

# =============================================================================
# Common Environment Configuration
# =============================================================================
# Note: use vim here so that if Neovim isn't setup, we gracefully fall back.
export EDITOR=vim

# If there is a screenshot directory, use it by default.
if [ -d "$HOME/screenshot" ]; then
    export GRIM_DEFAULT_DIR="$HOME/screenshot"
fi

# =============================================================================
# PATH
# =============================================================================
if [ -d "$HOME/.local/bin" ]; then
    export PATH="$HOME/.local/bin:$PATH"
fi

if [ -f "$HOME/.cargo/env" ]; then
    . "$HOME/.cargo/env"
elif [ -d "$HOME/.cargo/bin" ]; then
    export PATH="$HOME/.cargo/bin:$PATH"
fi

if [ -f ~/.fzf.zsh ]; then
    source ~/.fzf.zsh
fi

export JAVA_HOME="$local_install_dir/jdk"
if [ -d "$JAVA_HOME/bin" ]; then
    export PATH="$JAVA_HOME/bin:$PATH"
fi

export COURSIER_HOME="$HOME/.local/share/coursier"
if [ -d "$COURSIER_HOME/bin" ]; then
    export PATH="$COURSIER_HOME/bin:$PATH"
fi

export GO_HOME="$local_install_dir/go"
if [ -d "$GO_HOME/bin" ]; then
    export PATH="$GO_HOME/bin:$PATH"
    export GOPATH="$HOME/.local/go"
    export PATH="$GOPATH/bin:$PATH"
fi

export N_PREFIX="$HOME/.n"
if [ -d "$N_PREFIX/bin" ]; then
    export PATH="$N_PREFIX/bin:$PATH"
fi

# =============================================================================
# Additional FZF Setup
# =============================================================================
export FZF_CTRL_T_OPTS="
  --walker-skip .git,node_modules,target
  --preview 'bat -n --color=always {}'
  --bind 'ctrl-/:change-preview-window(down|hidden|)'"

# =============================================================================
# MAN PATH -- Support locally installed manpages
# =============================================================================
export MANPATH=$MANPATH:/home/pfm/.local/share/man

# =============================================================================
# SSH Agent Management
# =============================================================================
# Start ssh-agent if it is not already running. If it is running, ensure the
# environment variables are set properly.

ssh_agent_sock_file="$HOME/.ssh-agent-sock"
ssh_agent_pid_file="$HOME/.ssh-agent-pid"

touch $ssh_agent_sock_file
touch $ssh_agent_pid_file

if ps -p $(cat $ssh_agent_pid_file) > /dev/null 2>&1; then
    export SSH_AUTH_SOCK="$(cat $ssh_agent_sock_file)"
    export SSH_AGENT_PID="$(cat $ssh_agent_pid_file)"
else
    # Start a new instance of the SSH agent.
    eval "$(ssh-agent)"

    # Record the new settings in the agent tracking files.
    echo $SSH_AUTH_SOCK > $ssh_agent_sock_file
    echo $SSH_AGENT_PID > $ssh_agent_pid_file
fi

# =============================================================================
# Custom Functions
# =============================================================================

# This function helps get back to the git root, which is really commonly useful
# when deep in a source directory. Aliased to `gr`.
function jump-to-git-root {
    local git_root="$(git rev-parse --show-toplevel 2>/dev/null)"
    if [[ -z $git_root ]]; then
        >&2 echo 'Not a Git repo!'
        return 1
    fi
    local current_pwd=$(pwd)
    OLDPWD=$current_pwd
    cd $git_root
}

# =============================================================================
# Aliases
# =============================================================================
alias gr=jump-to-git-root

if command -v eza > /dev/null 2>&1; then
    alias ls='eza'
    alias ll='eza -l'
else
    if $logging_enabled; then
        echo "[warn] eza is not setup! Attempting to use exa" >> "$log_file"
    fi
    if command -v exa > /dev/null 2>&1; then
        alias ls='exa'
        alias ll='exa -l'
    else
        if $logging_enabled; then
            echo "[warn] exa is not setup! Using the system ls" >> "$log_file"
        fi
    fi
fi

if command -v nvim > /dev/null 2>&1; then
    alias vim='nvim'
else
    if $logging_enabled; then
        echo "[warn] Neovim is not setup! Using the system vim" >> "$log_file"
    fi
fi

if command -v podman > /dev/null 2>&1; then
    alias docker='podman'
    export DOCKER_HOST=unix:///run/podman/podman.sock
    export TESTCONTAINERS_RYUK_DISABLED=true
else
    if $logging_enabled; then
        echo "[warn] Podman is not setup! The 'docker' command will not be available." >> "$log_file"
    fi
fi

# =============================================================================
# Scala/SBT Setup
# =============================================================================
if command -v sbt > /dev/null 2>&1; then
    # This includes fixes for Scala until it supports JVM 24 properly and 
    # removes the use of deprecated methods (sun.misc.Unsafe)
    export SBT_OPTS="-XX:+UseG1GC -Xmx2048m --sun-misc-unsafe-memory-access=allow --enable-native-access=ALL-UNNAMED"
fi

# =============================================================================
# Git Command Completion
# =============================================================================

zstyle ':completion:*:*:git:*' script ~/.zsh/git-completion.bash

# This directory contains _git, a git completion script.
# We _also_ need the BASH one that is referenced above.
fpath=(~/.zsh $fpath)

# =============================================================================
# Initialize Starship
# =============================================================================
eval "$(starship init zsh)"

# =============================================================================
# Enable Command Syntax Highlighting
# This must be the last item in this file.
# =============================================================================
source $local_install_dir/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
eval "$(atuin init zsh)"
