#!/bin/bash

ME=$(basename $0);

set -o pipefail

source //etc/common-utils.rc
source //etc/ec2.rc


function connect_node()
{
    iids=$(ec2-describe-tags --region $ec2_placement_region -F resource-type=instance -F key=Name -F value=$1 | awk '{print $3}')
    if [ -z "$iids" ]; then
	echo "No instance found for $1"
	exit
    fi
    instance=$(ec2-describe-instances --region $ec2_placement_region $iids | awk '/running/ {print $5}')
    if [ $(echo $instance | wc -w) -ne 1 ]; then
	echo "Multiple running instances ($instance) found for $1"
	exit
    fi
    echo "Running ssh $instance"
    ssh $instance
}


function show_help()
{
    usage_banner;
    cat <<EOF

Usage:  $ME [-h] GLUSTER-NODE-ID

Attach GLUSTER-NODE-ID to current instance.
GLUSTER-NODE-ID is another Gluster Storage Virtual Appliance instance
identified by its node tag (e.g i-gluster-XXX)

Miscellaneous:
  -h                        display this help and exit

Example:
  $ME i-gluster-7
EOF
}


function main()
{
    # Parse command line arguments.
    while getopts :h OPT; do
	case "$OPT" in
	    h)
		show_help
		exit 0
		;;
	    \?)
                # getopts issues an error message
		echo "Invalid option: -$OPTARG"
		show_help
		exit 1
		;;
	esac
    done

    # Remove the switches we parsed above.
    shift `expr $OPTIND - 1`

    # We want only one non-option argument.
    if [ $# -ne 1 ]; then
	show_help
	exit 1
    fi

    node=$1

    assert_creds;

    connect_node $node;
}


main "$@";
