#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
#EL_REPORTS="1"
#el_make_environment
set -e

if [[ -z "$3" ]]; then
    #echo "Specify session name as the first argument"
    echo -e "This tool runs commands in detached tmux sessions"
    echo -e "Usage: $(basename $0) group win-name \"commands\""
    echo -e "where, group is an identifier for a sort of specific tasks, win-name is the name that you will have on the 'window tab' of tmux, commands are the commands to run on it"
    echo -e "example: $(basename $0) sendfiles 'to myserver' \"scp hugefile.iso user@myserver:uploaded/\""
    exit
fi

# if we come from an existing tmux we need to allow to run new ones (they are not really nested)
unset TMUX

group_session="$1"
shift
win_name="$1"
shift

if [[ "${group_session}" = "$win_name" ]] ; then
    el_error "group and windows names should be different"
    exit 1
fi

# precache for less pause
precache tmux 1>/dev/null 2>&1

# force to not running is_interactive when we are not (for example, run from a cronjob)
if ((is_interactive)) || ((FORCE_INTERACTIVE)) ; then
    _FORCE_INTERACTIVE=yes
else
    _FORCE_INTERACTIVE=no
fi

# note since there may be some missing env variables that will give us an empty result (if run from cronjobs for example), let's run this from a bash sub-wrapper
tmux_nb="$(bash -c "tmux ls 2>/dev/null" | grep "^${group_session}: " | wc -l)"

# create a first group
if [[ "$tmux_nb" == "0" ]]; then
    echo "Launching new tmux group session $group_session ..."

    # create a new group with a temporal process to attach the first job on the existing group
    tmux new-session -d -s $group_session -n "${win_name}" -x 400 -y 100 "sleep 10 ; exit" \; setenv FORCE_INTERACTIVE "$_FORCE_INTERACTIVE"
    LC_ALL=C sleep 0.5
fi

# Make sure we are not already in a tmux session
if [[ -n "$TMUX" ]]; then
    el_error "TMUX variable is set, unset it if you want to force it"
else
    # Kill defunct sessions first
    old_sessions=$(bash -c "tmux ls 2>/dev/null" | egrep "^[0-9]{14}.*[0-9]+\)$" | cut -f 1 -d:)
    for old_session_id in $old_sessions; do
        [[ -z "$old_session_id" ]] && continue
        tmux kill-session -t $old_session_id
    done

    # run things in a new window
    #tmux new-window -t "${group_session}:+" -n "$win_name" "$@"
    tmux new-window -t "${group_session}" -n "$win_name" "$@" \; setenv FORCE_INTERACTIVE "$_FORCE_INTERACTIVE"

    echo "Jobs run in a background tmux"
    echo "Tip: run 'tmux ls' to list tmux sessions or go to it with 'tmux attach -t $group_session'"

fi
