#############
# Debugging #
#############

# Detect if we have GNU coreutils or BSD
if date --version > /dev/null 2>&1 ;then
    # Global counter that can be used to diagnose duplicated calls
    printf "0" > /dev/shm/debug_counter
    debug_counter_inc() {
        count="$(cat /dev/shm/debug_counter)"
        ((count++))
        printf "%d" "$count" > /dev/shm/debug_counter
    }
    debug_counter_print(){
        printf "%d" "$(cat /dev/shm/debug_counter)"
    }
fi

###################
# Update checking #
###################

check_rc_update () {
    # Get rc dir path
    RC_PATH=$(dirname "$(realpath -- "${(%):-%x}")")

    CUR_DIR="$(pwd)"
    cd $RC_PATH

    # In case the network is down, don't lock the terminal
    GIT_SSH_COMMAND='ssh -oBatchMode=yes' GIT_TERMINAL_PROMPT=0 timeout 6 git fetch > /dev/null 2>&1

    # Timeout returns 124 on timeout
    if [ "$?" -ge "124" ]; then
        echo 'git_network_unreachable' >> /dev/shm/prompt_msg
    fi

    # Check if the repo is clean
    git_st=$(command git status --porcelain -b 2> /dev/null)
    if $(echo "$git_st" | grep '^## .*ahead' > /dev/null 2>&1); then
        echo 'git_unpushed' >> /dev/shm/prompt_msg
    elif $(echo "$git_st" | grep '^## .*behind' > /dev/null 2>&1); then
        echo 'update_rc' >> /dev/shm/prompt_msg
    fi

    cd $CUR_DIR
}

check_sys_update () {
    case $(lsb_release -i | awk -F ':\t' '/Distributor ID/{print $2}') in
        Arch|Artix)
            nb_maj=$(checkupdates | wc -l);;
        Debian|Ubuntu)
            nb_maj=$(aptitude search '~U' | wc -l);;
        VoidLinux)
            nb_maj=$(xbps-install -Sun | wc -l);;
    esac
    if [ $nb_maj -gt 0 ]; then
        echo "update_sys $nb_maj" >> /dev/shm/prompt_msg
    fi
}

############
# Commands #
############

# Do the update
uprc () {
    RC_PATH=$(dirname "$(readlink -f ${(%):-%x})")
    cd $RC_PATH
    git pull --rebase --stat origin master
    $RC_PATH/install.sh
    cd - &> /dev/null
    source $HOME/.zshrc
}

# Syntax coloration for man
man() {
  env \
    LESS_TERMCAP_mb="$(printf "%s" "$fg_bold[red]")" \
    LESS_TERMCAP_md="$(printf "%s" "$fg_bold[red]")" \
    LESS_TERMCAP_me="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_se="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_so="$(printf "%s" "$bg[black]$fg[yellow]")" \
    LESS_TERMCAP_ue="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_us="$(printf "%s" "$fg_bold[blue]")" \
    man "$@"
}

# Youtube audio search
ymsearch() {
    mpv --ytdl-format=bestaudio ytdl://ytsearch:"$(xsel -ob)"
}

# Kitty terminfo setup for ssh
ssh_kitty () {
    kitty +kitten ssh "$@"
}

mp4togif() {
    if [ "$1" = "-h" ] || [ "$#" -ne "2" ]; then
        >&2 echo "Usage: $0 <input.mp4> <output.gif>"
        return 1
    fi

    ffmpeg -i "$1" -vf "fps=10,scale=320:-1:flags=lanczos,split[x][z];[z]palettegen[y];[x][y]paletteuse" -loop 0 "$2"
}

# vim: ft=zsh