#!/bin/bash

read -r -d '' doc << EOM
Wrapper for Tmuxinator
EOM

eval "$(shlib)"

# ---------- Command-line Arguments ----------
export USAGE_GRAMMAR=(
    "[-d] [-v] [-MUX_CMD [ARGS]]"
    "[-d] [-v] MUX_SESSION"
    "-h"
)

# shellcheck disable=SC2154
read -r -d '' help << EOM
$(usage)

${doc}

Positional Arguments:
    MUX_SESSION     The tmuxinator session to start.

Optional Arguments:
    -d | --debug
        Enable debug mode.

    -MUX_CMD [ARGS]
        A valid tmuxinaor command prefixed with a single dash. This option
        has the same syntax as specified by tmuxinator and thus MAY have
        arguments.

    -h | --help
        View this help message.

    -v | --verbose
        Enable verbose output.
EOM

while [[ -n "$1" ]]; do
    case $1 in
       -d|--debug )
           debug=true
           ;;
       -h|--help )
           echo "${help}"
           exit 0
           ;;
       -v|--verbose )
           verbose=true
           ;;
       -- )
           shift
           break
           ;;
       * )
           break
           ;;
    esac
    shift
done

if [[ "${debug}" = true && "${verbose}" = true ]]; then
    PS4='$LINENO: '
    set -x
fi

if [[ $# -lt 1 ]]; then
    die "$(usage)" 2
fi

# ---------- Main ----------
MUX_CONFIG_DIR=~/.config/tmuxinator

case $1 in
    '-'* )
        CMD=${1#-}; shift
        if [[ 'edit' == "$CMD"* ]]; then
            if [[ -n "$1" ]]; then
                tmuxinator edit "$1"
            else
                tmuxinator edit "$(tm-session-name)"
            fi
        else
            tmuxinator "$CMD" "$@"
        fi;;
    * )
        SESSION_NAME=$1; shift
        if [[ ! -f $MUX_CONFIG_DIR/$SESSION_NAME.yml ]]; then
            erb name="$SESSION_NAME" "$MUX_CONFIG_DIR"/default.yml > "$MUX_CONFIG_DIR"/"$SESSION_NAME".yml
        fi

        root="$(tm-session-root --get "$SESSION_NAME")"
        tmuxinator start "$SESSION_NAME" root="${root}"

        if [[ -n "$1" ]]; then
            SOCKET_NAME="$1"; shift
            tmux -L "$SOCKET_NAME" attach -t "$SESSION_NAME"
        else
            tmux switch-client -t "$SESSION_NAME"
        fi
        ;;
esac
