#!/usr/bin/env bash

set -eu

prgname=${0##*/}

# ----------------------------------------

cmd() {
    "${tmux[@]}" "$@"
}

new() {
    cmd new -d -x - -y - -s "$session" -e SHOME="$PWD" "$@"
}

neww() {
    cmd neww -t "=$session" "$@"
}

# ----------------------------------------

adm() {
    cd ~
    ext
}

aux() {
    cd ~

    local notesdir=~/projects/notes/src
    new -n notes -c "$notesdir" trun e \
        \; set remain-on-exit on \
        \; set main-pane-width 116 \
        \; splitw -h -c "$notesdir" \
        \; selectl main-vertical

    neww -n mail trun mutt \
        \; set remain-on-exit on

    neww -n chat trun weechat -a \
        \; set remain-on-exit on

    neww -n feeds trun newsboat -q \
        \; set remain-on-exit on

    cmd selectw -t "=$session:1"
}

base() {
    new
}

ext() {
    new trun ranger \
        \; set remain-on-exit on

    neww trun ee \
        \; set remain-on-exit on \
        \; set main-pane-width 84 \
        \; splitw -h \
        \; selectl main-vertical
}

mon() {
    cd ~

    new -n top trun conky -q \
        \; set remain-on-exit on \
        \; set main-pane-width 45 \
        \; splitw -h trun htop \
        \; selectl main-vertical

    neww -n journal trun journalctl --system -f \
        \; set remain-on-exit on \
        \; splitw -v trun journalctl --user -f \
        \; selectp -t :.0 \
        \; selectl even-vertical

    neww -n sstat trun pgx sstat \
        \; set remain-on-exit on

    neww -n iftop trun iftop -i eth0 \
        \; set remain-on-exit on \
        \; splitw -v trun iftop -i wlan0

    neww -n logs -c /var/log

    cmd selectw -t "=$session:1"
}

tmp() {
    cd ~/tmp
    base
}

wrk() {
    cd ~/projects
    ext
}

# ----------------------------------------

_usage() {
    echo "usage: $prgname [-d] [-s socket] [template] [session]"
}
usage() { _usage; exit 0; }
usage_err() { _usage; exit 2; } >&2

socket=default
declare -i attach=1
while getopts ds:h opt; do
    case $opt in
        d) attach=0 ;;
        s) socket=$OPTARG ;;
        h) usage ;;
        *) usage_err ;;
    esac
done
shift $((OPTIND-1))

# ----------------------------------------

tmux=(tmux -L "$socket")

templates=(
    adm
    aux
    base
    ext
    mon
    tmp
    wrk
)

if (( $# )); then
    template=$1
    session=${2:-$template}
else
    template=ext
    session=-
fi

if [[ $template = - ]]; then
    printf '%s\n' "${templates[@]}"
    exit
fi

for i in "${templates[@]}"; do [[ $template = "$i" ]] && break; done
if [[ $template != "$i" ]]; then
    echo "$prgname: $template: No such template" >&2
    exit 2
fi

if [[ $session = - ]]; then
    session=$PWD/
    session=${session/#$HOME\//\~/}
    session=${session%/}
fi

set +e
if ! cmd has -t "=$session" &>/dev/null; then
    (set -e; $template)
fi

if (( attach )); then
    exec "${tmux[@]}" attach -t "=$session"
fi
