#!/bin/sh
#/ Usage: ghe-host-check [<host>]
#/ Verify connectivity with the GitHub Enterprise host. When no <host> is
#/ provided, the $GHE_HOSTNAME configured in backup.config is assumed.
set -e

# Bring in the backup configuration.
cd $(dirname "$0")/..
. share/github-backup-utils/ghe-backup-config

# Use the host provided on the command line if provided, or fallback on the
# $GHE_HOSTNAME configured in backup.config when not present.
host="${1:-$GHE_HOSTNAME}"

# Options to pass to SSH during connection check
options="
    -o PasswordAuthentication=no
    -o ConnectTimeout=5
    -o ConnectionAttempts=1
"

# Split host:port into parts
port=$(ssh_port_part "$host")
hostname=$(ssh_host_part "$host")

set +e
output=$(echo "ghe-negotiate-version backup-utils $BACKUP_UTILS_VERSION" | ghe-ssh -o BatchMode=no $options $host -- /bin/sh 2>&1)
rc=$?
if [ $rc = 127 ]; then
  # ghe-negotiate-version not found, fallback to reading version file
  legacy_version_output="1"
  output=$(echo "cat \"$GHE_REMOTE_METADATA_FILE\" 2>/dev/null || exit 101" | ghe-ssh -o BatchMode=no $options $host -- /bin/sh 2>&1)
  rc=$?
fi
set -e

if [ $rc -ne 0 ]; then
    case $rc in
        255)
            if echo "$output" | grep -i "port 22: connection refused" >/dev/null; then
                exec "bin/$(basename $0)" "$hostname:122"
            fi

            echo "$output" 1>&2
            echo "Error: ssh connection with '$host' failed" 1>&2
            echo "Note that your SSH key needs to be setup on $host as described in:" 1>&2
            echo "* https://enterprise.github.com/help/articles/adding-an-ssh-key-for-shell-access" 1>&2
            ;;
        101)
            echo "Error: couldn't read GitHub Enterprise fingerprint on '$host' or this isn't a GitHub appliance." 1>&2
            ;;
        1)
            if [ "${port:-22}" -eq 22 ] && echo "$output" | grep "use port 122" >/dev/null; then
                exec "bin/$(basename $0)" "$hostname:122"
            else
                echo "$output" 1>&2
            fi
            ;;

    esac
    exit $rc
fi

if [ -z "$legacy_version_output" ]; then
  version=$(echo "$output" | sed -n 's/GitHub Enterprise version \(.*\)/\1/p')
else
  version=$(echo "$output" | grep version | cut -d'"' -f4)
fi

if [ -z "$version" ]; then
    echo "Error: failed to parse version on '$host' or this isn't a GitHub appliance." 1>&2
    exit 2
fi

echo "Connect $hostname:$port OK (v$version)"
