#!/bin/bash

LIB_DIR="$( dirname "$( realpath "$0" )" )/../lib"
if [[ -f "$LIB_DIR/eeadmtools/helpers" ]]; then
    # shellcheck source=/dev/null
    source "$LIB_DIR/eeadmtools/helpers"
else
    # shellcheck source=/dev/null
    source "$LIB_DIR/helpers"
fi

function usage() {
    default_usage \
      "[host]" \
      "  host\t\t\tHostname"

}
handle_args "$@"

HOST=$1
[[ -z "$HOST" ]] && usage

# Remove "-from-pXX" suffix
# shellcheck disable=SC2001
HOST=$( sed 's/-from-\(prs\|pa[2-3]\)$//' <<< "$HOST" )

# Detect EeID and add "ee-" prefix if not present
EEID=$( grep -E '^[^-]+-.*' <<< "$HOST" | sed 's/^\([^-]\+\)-.*$/\1/' )
( [[ -z "$EEID" ]] || is_reserved_eeid "$EEID" ) && HOST="ee-$HOST"

HOST=$( zenity --entry --text="Please input the server name as expected by EeSSH:" --entry-text="$HOST" )
[[ -z "$HOST" ]] && exit 1

# Special case: tsh
if [[ "${TSH_EEID_TO_PROXY_HOST[$EEID]:-null}" != "null" ]] && \
    zenity --question --title "Use TSH ?" --text "Connect to $HOST using teleport?"
then
    xdg-open "eetsh://$HOST"
else
    xdg-open "eessh://$HOST"
fi
