#!/bin/sh

# Use neovim for vim if present
[ -x "$(command -v nvim)" ] && alias vim="nvim" vimdiff="nvim -d"

# Use $XINITRC variable if file exists.
[ -f "$XINITRC" ] && alias startx="startx $XINITRC"

# sudo not required for some system commands
for x in mount umount sv pacman updatedb su ; do
    alias $x="sudo $x"
done

# Verbosity and settings that you pretty much just always are going to want.
alias \
    ...="cd .." \
    ...="cd ../.." \
    ....="cd ../../.." \
    .....="cd ../../../.." \
    df="df -h" \
    du="du -h" \
    free="free -m" \
    cp="cp -iv" \
    mv="mv -iv" \
    rm="rm -vI" \
    bc="bc -ql" \
    mkd="mkdir -pv" \
    yt="youtube-dl --add-metadata -i" \
    yta="yt -x -f bestaudio/best" \
    ffmpeg="ffmpeg -hide_banner" \
    tmux="tmux -f ~/.config/tmux/tmux.conf" \
    aider="aider --config ~/.config/aider/aider.yaml"

alias ff="fzf --preview 'bat --style=numbers --color=always {}'"
alias eff='$EDITOR "$(ff)"'

if command -v eza &> /dev/null; then
    alias ls='eza -lh --group-directories-first --icons=auto'
    alias la='ls -al'
    alias lt='eza --tree --level=2 --long --icons --git'
    alias lta='lt -a'
fi

if command -v zoxide &> /dev/null; then
    alias cd="zd"
    zd() {
        if (( $# == 0 )); then
            builtin cd ~ || return
        elif [[ -d $1 ]]; then
            builtin cd "$1" || return
        else
            if ! z "$@"; then
                echo "Error: Directory not found"
                return 1
            fi

            printf "\U000F17A9 "
            pwd
        fi

        if [[ -n $TMUX ]]; then
            tmux rename-window "$(basename "$PWD")"
        fi
    }
fi

# Colorize commands when possible.
alias \
    grep="grep --color=auto" \
    diff="diff --color=auto" \
    ccat="highlight --out-format=ansi"

# Abbreviating long commands
alias \
    ka="killall" \
    YT="youtube-viewer" \
    sdn="sudo shutdown -h now" \
    v="$EDITOR" \
    cl="clear" \
    p="sudo pacman" \
    ll="ls -AhlFt --group-directories-first --time=atime --color=auto --time-style=long-iso" \
    ag="alias | grep" \
    lc="clone_from_labs" \
    gc="clone_from_github" \
    dgit="git --git-dir ~/.config/dotfiles/.git --work-tree=$HOME" \
    .z="source ~/.config/shell/profile" \
    .a="source ~/.config/shell/aliasrc" \
    testmic="arecord -vv -f dat /dev/null" \
    notes="cd ~/Tower/Notes && nvim ." \
    aid="aider"

# Dev
alias \
    sail='[ -f sail ] && sh sail || sh vendor/bin/sail' \
    yi="yarn install" \
    y="yarn" \
    ci="composer install" \
    c="composer" \
    tk="go-task" \
    mux="tmuxinator" \
    mex="tmuxinator stop-all" \
    lg="lazygit"

# Translating
alias \
    ro="trans ro:en -j -- " \
    roi="trans ro:en -i" \
    enr="trans en:ro -j -- " \
    enri="trans en:ro -i"

alias d='docker'
alias dc='docker compose'
alias t='tmux attach || tmux new -s Work'
e() { if [ "$#" -eq 0 ]; then command nvim . ; else command nvim "$@"; fi; }

open() (
  xdg-open "$@" >/dev/null 2>&1 &
)

function tf() {
    php artisan test --filter="$*"
}

function dut() {
    threshold=${1:-5}
    sudo du -hax -t"${threshold}G" /* --exclude=/{proc,sys,dev,run}
}

function gh() {
    local -a commands=(
      "Recover deleted file:                   git checkout HEAD -- <file>"
      "Revert previous commit keeping changes: git revert --no-commit HEAD~1"
      "Undo merge/pull that caused conflicts:  git revert -m 1 HEAD~1"
      "Abort rebase:                           git rebase --abort"
      "Unstage a file:                         git restore --staged <file>"
      "Undo a pushed commit:                   git reset --hard HEAD~1 && git push --force"
    )

    echo "Git First-Aid:"
    echo "--------------------------------"

    for i in {1..${#commands[@]}}; do
      echo "$i) ${commands[$i]}"
    done

    echo "--------------------------------"
}

# Clone from labs
function cll() {
    git clone "git@labs.scarif.space:chris/$1" "${@:2}"
}

# Clone from github
function clg() {
    git clone "https://github.com/$1" "${@:2}"
}

function lp() {
    lsof -i -P -n $@ | grep LISTEN
}

# Check if main exists and use instead of master
function git_main_branch() {
  command git rev-parse --git-dir &>/dev/null || return
  local branch
  for branch in main trunk; do
    if command git show-ref -q --verify refs/heads/$branch; then
      echo $branch
      return
    fi
  done
  echo master
}

# Yazi shortcut that allows setting the current working directory on exit
function -() {
    local tmp="$(mktemp -t "yazi-cwd.XXXXXX")" cwd
    yazi "$@" --cwd-file="$tmp"
    IFS= read -r -d '' cwd < "$tmp"
    [ -n "$cwd" ] && [ "$cwd" != "$PWD" ] && builtin cd -- "$cwd"
    rm -f -- "$tmp"
}

# Git aliases
alias \
    g="git" \
    ga="git add" \
    dga="dgit add -f" \
    dgc="dgit commit" \
    dgcm="dgit commit -m" \
    dgs="dgit status" \
    dgd="dgit diff" \
    dgdc="dgit diff --cached" \
    dgp="dgit push" \
    dgup="dgit pull --rebase" \
    gaa="git add --all" \
    gb="git branch" \
    gba="git branch -a" \
    gbd="git branch -d" \
    gbD="git branch -D" \
    gbs="git bisect" \
    gbsb="git bisect bad" \
    gbsg="git bisect good" \
    gbsr="git bisect reset" \
    gbss="git bisect start" \
    gc="git commit -v" \
    gc!="git commit -v --amend" \
    gcn!="git commit -v --no-edit --amend" \
    gca="git commit -v -a" \
    gca!="git commit -v -a --amend" \
    gcan!="git commit -v -a --no-edit --amend" \
    gcam="git commit -a -m" \
    gcmsg="git commit -m" \
    gcm="git checkout $(git_main_branch)" \
    gco="git checkout" \
    gcb="git checkout -b" \
    gf="git fetch" \
    gfa="git fetch --all --prune" \
    gd="git diff" \
    gdc="git diff --cached" \
    gl="git pull --no-rebase" \
    glg="git log --stat" \
    glgg="git log --graph" \
    glo="git log --oneline --decorate" \
    glgp="git log --stat -p" \
    gm="git merge" \
    gp="git push" \
    grb="git rebase" \
    grba="git rebase --abort" \
    grbc="git rebase --continue" \
    gsb="git status -sb" \
    gsh="git show" \
    gsps="git show --pretty=short --show-signature" \
    gsta="git stash push" \
    gstaa="git stash apply" \
    gstp="git stash pop" \
    gstl="git stash list" \
    gsts="git stash show --text" \
    gup="git pull --rebase" \
    nah="git reset --hard; git clean -df" \
    gapa="git add --patch -A" \
    gun="git reset --" \
    glgm="git log --stat --author=christopher" \
    glgpm="git log --stat -p --author=christopher"


alias \
    cat="bat" \
    ls="eza --icons=always" \
    fullClean="nix-collect-garbage --delete-old; sudo nix-collect-garbage -d; sudo /run/current-system/bin/switch-to-configuration boot" \
    rebuild="sudo nixos-rebuild switch --flake ~/.config/nixos/" \
    fullRebuild="sudo nixos-rebuild switch --flake ~/.config/nixos/ && home-manager switch --flake ~/.config/nixos/" \
    homeRebuild="home-manager switch --flake ~/.config/nixos/"
