#!/bin/bash

# File: tmux-hosts
#
# Description: This script allows you to open groups of hosts in 2x2 tmux panes
#
# Package: AniNIX/Ubiqtorate
# Copyright: WTFPL
#
# Author: DarkFeather <ircs://irc.aninix.net:6697/DarkFeather>

# Sanity
set -Eo pipefail

# Defaults
group=all
offset=0
unset inventory

function usage() { 
    # Show helptext
    # param retcode: what to exit
    retcode="$1"
    echo "Usage: $0 [ -o offset ] [-g group ] -i inventory.yml" 
    echo "       $0 -h"
    echo "Group is optional -- add it if you only want to look at a specific subset."
    echo "Add -v for verbosity."
    exit "$retcode"
}

function tmuxHosts() {
    # Open hosts in Tmux -- ported from pnp/misc-scripts.git geotmux
    # param host1: the first host
    # param host2: the second host
    # param host3: the third host
    # param host4: the fourth host
    host1="$1"
    host2="$2"
    host3="$3"
    host4="$4"
    name="$group-$offset"

    # If no TMUX session started, then add one with four panes.
    if [ -z "$TMUX" ]; then 
        tmux new-session -s "$name" -d "/bin/bash -l -c ssh\\ $host1"
        tmux select-window -t "$name":0
        tmux split-window "/bin/bash -l -c ssh\\ $host2"
        tmux split-window -h -t 0 "/bin/bash -l -c ssh\\ $host3"
        tmux select-window -t "$name":1
        tmux split-window -h -t 2 "/bin/bash -l -c ssh\\ $host4"
        tmux setw synchronize-panes
        tmux a -d -t "$name"
    # Otherwise, add a new window to the current session with all four sessions.
    else 
        tmux new-window -n "$name" "/bin/bash -l -c ssh\\ $host1"
        tmux select-window -t "$name"
        tmux split-window "/bin/bash -l -c ssh\\ $host2"
        tmux select-window -t "$name"
        tmux split-window -h -t 0 "/bin/bash -l -c ssh\\ $host3"
        tmux select-window -t "$name"
        tmux split-window -h -t 2 "/bin/bash -l -c ssh\\ $host4"
        tmux setw synchronize-panes
        tmux select-window -t "$name"
    fi
}

# main
if [ "$(basename $0)" == "tmux-hosts" ]; then
    while getopts 'g:hi:o:v' OPTION; do
        case "${OPTION}" in
            g) group="${OPTARG}" ;;
            h) echo Open Ansible hosts in TMUX panes.; usage 0 ;;
            i) inventory="${OPTARG}" ;;
            o) offset="${OPTARG}" ;;
            v) set -x ;;
            *) usage 1 ;;
        esac
    done
    
    if [ -z "$inventory" ]; then
        echo Need an inventory.
        usage 2;
    fi
    
    tmuxHosts $(ansible -i "$inventory" --list-hosts "$group"\
        | grep -v hosts\ \( \
        | sed 's/\s\+//g' \
        | if [ $offset -gt 0 ]; then tail -n +"${offset}"; else cat; fi \
        | head -n 4 \
        | tr '\n' ' ')
fi