#!/bin/bash

ME=$(basename $0);

set -o pipefail

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

show_all=no


function show_instances()
{
    outfile=/tmp/$ME.$$
    ec2-describe-tags --region $ec2_placement_region -F resource-type=instance -F key=Name -F value="i-$DOMAIN-*" > $outfile.desc-tags
    iids=$(awk '{print $3}' $outfile.desc-tags)
    if [ -n "$iids" ]; then
        ec2-describe-instances --region $ec2_placement_region --show-empty-fields --hide-tags $iids | grep -w '^INSTANCE' > $outfile.desc-instances
	for i in $iids; do
	    if ! grep -q $i $outfile.desc-instances; then
		sed -i "/$i/d" $outfile.desc-tags
		continue
	    fi
	    awk "/$i/ {print \$5}" $outfile.desc-instances >> $outfile.hostnames
	    awk "/$i/ {print \$6}" $outfile.desc-instances >> $outfile.states
	done
	awk '{print $5}' $outfile.desc-tags > $outfile.tags
	if [ "$show_all" = "yes" ]; then
            paste $outfile.hostnames $outfile.tags $outfile.states
	else
            paste $outfile.hostnames $outfile.tags $outfile.states | grep -v $(hostname -f)
	fi
    fi
    rm -f $outfile.*
}


function show_help()
{
    usage_banner;
    cat <<EOF

Usage:  $ME [-h] [-a]

List Gluster Storage Virtual Appliance instances excluding current
instance.

Miscellaneous:
  -a                        include current instance in listing.
  -h                        display this help and exit

Example:
  $ME
EOF
}


function main()
{
    # Parse command line arguments.
    while getopts :ha OPT; do
	case "$OPT" in
	    h)
		show_help
		exit 0
		;;
	    a)
		show_all=yes
		;;
	    \?)
                # 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 do not want non-option argument.
    if [ $# -ne 0 ]; then
	show_help
	exit 1
    fi

    assert_creds;

    show_instances;
}


main "$@";
