#!/usr/bin/env bash

ssh () {
    args="$@"
    regex=".+-([a-z]{3})\.(.+\.)?twitch.cloud"

    if [[ $args =~ $regex ]]; then
        if ! [[ -x "$(command -v teleport-bastion)" ]]; then
            echo "Teleport bastion was not found on your system.  Please ensure this is installed and configured properly."
            exit 1
        fi

        if ! (teleport-bastion status | grep -q enabled ); then
            echo "Notice: Running 'teleport-bastion -y enable' to enable teleport."
            teleport-bastion -y enable
            echo
        fi

        if [[ -n $BASH_VERSION ]]; then
            region=${BASH_REMATCH[1]};
        elif [[ -n $ZSH_VERSION ]]; then
            region=${match[1]};
        fi

        TC=csi-security-services-${region} command ssh $@
    else
        if ( echo $args | grep -q 'twitch.cloud' ); then
            echo "Warning: Unable to determine region for a twitch.cloud domain name. Teleport Remote has not been set for this session."
            echo
        fi

        command ssh $@
    fi
}

# This script allows for development by executing ./ssh-wrapper.sh <hostname> just as if it was the `ssh` command in your shell configuration.

ssh $@
