#!/usr/bin/env bash
set -euo pipefail

function usage() {
    SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
    echo "$SCRIPT_NAME: ssh to AWS GameLift fleet instance"
    echo "Usage:  $SCRIPT_NAME [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -f | --fleet-id FLEET_ID            set  fleet-id (default: \$FLEET_ID=${FLEET_ID:-none})"
    echo "  -i | --instance-id INSTANCE_ID      set instance-id (default: \$INSTANCE_ID=${INSTANCE_ID:-none})"
    echo "  -h | --help                         show this help message"
}

function parse_arguments () {
    SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
    eval set -- "$(getopt -o f:i:h --long fleet-id:,instance-id:,help -n "$SCRIPT_NAME" -- "$@")"
    while true; do
        case "$1" in
            -f | --fleet-id         ) FLEET_ID="$2"     ; shift ; shift ;;
            -i | --instance-id      ) INSTANCE_ID="$2"  ; shift ; shift ;;
            -h | --help             ) usage ; exit 0 ; shift ;;
            --                      ) shift ; break ;;
            *                       ) break ;;
        esac
    done

    if [[ $# -gt 0 ]]; then
        echo >&2 "ERROR: unknown arguments specified: " "$@"
        exit 1
    fi

    if [[ -z "${FLEET_ID:-}" ]]; then
        echo >&2 "ERROR: fleet-id not specified on command line or FLEET_ID environment variable; try --help"
        exit 1
    fi

    if [[ -z "${INSTANCE_ID:-}" ]]; then
        echo >&2 "ERROR: instance-id not specified on command line or INSTANCE_ID environment variable; try --help"
        exit 1
    fi
}

parse_arguments "$@"

# Get credentials for EC2 instance
INSTANCE_INFO="$(aws gamelift get-instance-access --instance-id "$INSTANCE_ID" --fleet-id "$FLEET_ID" --output json)"
# {
#     "InstanceAccess": {
#         "InstanceId": "i-090e5e2f016d7fe7b",
#         "IpAddress": "1.2.3.4"
#         "FleetId": "fleet-d192c0b6-5338-43b6-8dc9-5c23207e3ab8",
#         "OperatingSystem": "AMAZON_LINUX",
#         "Credentials": {
#             "UserName": "gl-user-remote",
#             "Secret": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----\n"
#         }
#     }
# }

# Save the RSA secret key into a temporary file that will be deleted on exit
PEM_FILE="$(mktemp --tmpdir="$HOME/.ssh" "gamelift-temp-XXX")"
trap 'set +e ; chmod +w "$PEM_FILE" 2>/dev/null ; rm -f "$PEM_FILE" 2>/dev/null' INT TERM ERR EXIT
echo "$INSTANCE_INFO" | jq -r ".InstanceAccess.Credentials.Secret" > "$PEM_FILE"
chmod 400 "$PEM_FILE"

# Connect via SSH
IP_ADDRESS="$(echo "$INSTANCE_INFO" | jq -r ".InstanceAccess.IpAddress")"
USERNAME="$(echo "$INSTANCE_INFO" | jq -r ".InstanceAccess.Credentials.UserName")"
ssh -i "$PEM_FILE" -o "StrictHostKeyChecking no" -o "UserKnownHostsFile /dev/null" "$USERNAME"@"$IP_ADDRESS"
