#!/bin/sh
#/ Usage: ghe-ssh [<option>...] <host> [<simple-command>...]
#/        echo 'set -o pipefail; <complex-command>...' | ghe-ssh [<option>...] <host> /bin/bash
#/ Helper to ssh into a GitHub instance with the right user and port. The first
#/ form should be used for simple commands; the second form should be used for
#/ complex commands that include pipelines or multiple commands.
set -e

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

opts="$GHE_EXTRA_SSH_OPTS"
while true; do
    case "$1" in
        -p|-l|-o)
            opts="$opts $1 $2"
            shift 2
            ;;
        --)
            echo "Error: illegal '--' in ssh invocation"
            exit 1
            ;;
        *)
            host="$1"
            shift
            break
            ;;
    esac
done

# Show usage with no host
[ -z "$host" ] && print_usage

# Shift off '--' if given immediately after host.
if [ "$1" = "--" ]; then
    shift
fi

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

# Add user / -l option
user="${host%@*}"
[ "$user" = "$host" ] && user="admin"
opts="-l $user $opts"

# Bail out with error if the simple command form is used with complex commands.
# Complex
if echo "$*" | grep "[|;]" >/dev/null || [ $(echo "$*" | wc -l) -gt 1 ]; then
    echo "fatal: ghe-ssh: Attempt to invoke complex command with simple command form." 1>&2
    echo "See ghe-ssh --help for more on correcting." 1>&2
    exit 1
fi

# Turn on verbose SSH logging if needed
$GHE_VERBOSE_SSH && set -x

# Exec ssh command with modified host / port args and add nice to command.
exec ssh -p $port $opts -o BatchMode=yes "$host" -- $GHE_NICE $GHE_IONICE "$@"
