#!/bin/bash

set -eu
set -o pipefail

host_path=""
command_group='tty'
command_name='terminal-window: fancy'

function usage
{
    retval="$1"
    case "$retval" in
        0)
            ;;
        *)
            exec 1>&2
            ;;
    esac
    echo "Usage: $0 --host-path dstromberg@localhost!root@localhost --command-group tty --command 'terminal-window: fancy'"
    echo
    echo "--command-group defaults to tty"
    echo "--command defaults to '$command_name'"
    echo "--host-path is a required option.  It accepts a deep-ssh bang path of hosts to ssh through."
    exit "$retval"
}

function starts_with_letter
{
    case "$1" in
        [a-zA-Z]*)
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

while [ "$#" -ge 1 ]
do
    case "$1" in
        --host-path|-h)
            # We no longer check fora host path starting with a letter, because we want to be able to do IP addresses.
            host_path="$2"
            shift
            ;;
        --command-group|-C)
            if [ "$#" -ge 2 ] && starts_with_letter "$2"
            then
                command_group="$2"
            else
                echo "$0: -C--command-group require a hostname" 1>&2
                usage 1
            fi
            shift
            ;;
        --command|-c)
            # command is a bash builtin, so we use command_name
            if [ "$#" -ge 2 ] && starts_with_letter "$2"
            then
                command_name="$2"
            else
                echo "$0: -c--command require a hostname" 1>&2
                usage 1
            fi
            shift
            ;;
        --help)
            usage 0
            ;;
        *)
            echo "$0: Unrecognized option: $1" 1>&2
            usage 1
            ;;
    esac
    shift
done

if [ "$host_path" = "" ]
then
    echo "$0: --host-path is a required option" 1>&2
    usage 1
fi

hcm.py --run-command-on-host-path "$command_group" "$command_name" "$host_path"