#!/bin/sh
prog=$(basename "$0")

exec_tmux () {
    tmuxconf_arg=
    tmuxconf=$HOME/.tmux.conf
    # ^^ the _current_ user's tmux.conf
    sockname=$(id -un)
    # ^^ name socket after invoker
    [ -e "$tmuxconf" ] && tmuxconf_arg=-f\ "$tmuxconf"
    # shellcheck disable=SC2086
    exec sudo -i tmux -L "$sockname" $tmuxconf_arg "$@"
}

exec_screen () {
    screenrc_arg=
    screenrc=$HOME/.screenrc
    # ^^ the _current_ user's screenrc
    sockname=$(id -un)
    # ^^ name socket after invoker
    [ -e "$screenrc" ] && screenrc_arg=-c\ "$screenrc"
    # shellcheck disable=SC2086
    exec sudo -i screen -D -R -S "$sockname" $screenrc_arg "$@"
    #                   ^^^^^ detach and attach to existing screen
}

case $1 in
    -screen)
        if ! command -v screen >/dev/null 2>&1; then
            echo >&2 "screen requested but not found"
            exit 127
        else
            shift
            exec_screen "$@"
        fi
        ;;
    -tmux)
        if ! command -v tmux >/dev/null 2>&1; then
            echo >&2 "tmux requested but not found"
            exit 127
        else
            shift
            exec_tmux "$@"
        fi
        ;;
    -h|-help)
        echo "Runs screen/tmux in sudo with a socket named after the invoker"
        echo "Usage:"
        echo "  $prog [<args>]                  Run tmux or screen, whichever is found first"
        echo "  $prog -tmux|-screen [<args>]    Run tmux or screen, whichever is specified;"
        echo "error out if not found"
        echo "<args> are passed directly to tmux/screen"
        exit
        ;;
esac

if command -v tmux >/dev/null 2>&1; then
    exec_tmux "$@"
elif command -v screen >/dev/null 2>&1; then
    exec_screen "$@"
else
    echo >&2 "No tmux or screen found"
    exit 127
fi
