#!/usr/bin/env bash

# inspect the tmux environment to determine what context the user is currently
# in. what's a context? a task or a bug, whose name matches either the current
# window or session name. a task is defined as anything that's not a bug and
# has a top level key in the database. bugs are top level keys that are only
# numbers
#
# this can also be called programmatically by scripts when they know the
# context is going to change.
#
# priority
# - arguments
# - window name matches a bug
# - window name matches a task
# - session name matches a bug
# - session name, regardless of match to task

IFS=' ' read -ra arguments      < <(echo "$1")

is_bug() {
    local what="$1"
    {
        [ "$what" -eq "$what" ] || [[ $what =~ pscale ]]
    } 2>/dev/null
}

# arguments override everything
if [[ ${arguments[0]} ]]; then
    if [ "${arguments[0]}" -eq "${arguments[0]}" ] 2>/dev/null; then
        # bug + description
        context="${arguments[0]}"
    else
        # something else
        context="$*"
    fi

# no args, detect from tmux
else
    [[ $TMUX ]] || exit 0
    IFS=' ' read -ra session_header < <(tmux display-message -p "#S")
    IFS=' ' read -ra window_header  < <(tmux display-message -p "#W")

    # window name bug?
    if is_bug "${window_header[0]}"; then
        # bug
        context="${window_header[0]}"

    # window name task?
    elif [[ $( d "${window_header[*]}" -k ) ]]; then
        context="${window_header[*]}"

    # session name bug?
    elif is_bug "${session_header[0]}"; then
        # bug
        context="${session_header[0]}"

    # session name task
    else
        # task
        context="${session_header[*]}"
    fi
fi

[[ $context ]] &&
    timeout 0.05 d current-context = "$context"
