#!/bin/bash


ME=$(basename $0);

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


TAGDUMP=;


function search_name()
{
    curr_tags=;

    while read line; do
        if [ -z "$line" ]; then
            continue
        fi
        set $line;
        if [ $# -eq 0 ]; then
            continue
        fi
        restype=$2;
        id=$3;
        key=$4;
        val=$5;

        if [ $key != "Name" ]; then
            continue;
        fi

        if [ $id = $instance ]; then
            if [ ! -z "$val" -a -z "${val##i-$DOMAIN*}" ]; then
                # stick on to the current name
                echo $val;
                return;
            fi
        fi

        [ -z ${val##i-$DOMAIN*} ] && curr_tags="$curr_tags $val";
    done

    i=1;
    tag=;
    while true; do
        tag=i-${DOMAIN}-${i};
        if ! exists_in_list $tag $curr_tags $just_tagged; then
            break;
        fi
        i=$(($i + 1));
    done

    echo $tag;
}


function get_a_name()
{
    echo "$TAGDUMP" | search_name;
}


function tag_instance()
{
    if [ -z "$TAGDUMP" ]; then
        echo -n "Preparing for tagging ...";
        TAGDUMP=$(ec2-describe-tags --region $ec2_placement_region);
        echo;
    fi

    echo -n "Calculating a name for $instance ...";
    name=$(get_a_name);
    echo " $name";

    echo "Tagging instance ($instance) with Name ($name) and Domain ($DOMAIN) ..."
    ec2-create-tags --region $ec2_placement_region $instance --tag Name=$name --tag Domain=$DOMAIN >/dev/null 2>&1 &

    just_tagged="$just_tagged $name";
}


function show_help()
{
    usage_banner;
    cat <<EOF

Usage:  $ME [-h]

Add Gluster Storage Virtual Appliance ID to this instance.

WARNING: This is an internal tool.  You should not invoke this directly.
         Refer gluster-ami-bootstrap or gluster-ami-newinstance tool
         for more detail.

Miscellaneous:
  -h                        display this help and exit

Example:
  $ME
EOF
}


function main()
{
    if [ "$1" = "-h" ]; then
	show_help
	exit 1
    fi

    instances="$@";

    if [ -z "$instances" ]; then
        instance=$ec2_instance_id;
        tag_instance $instance;
        return;
    fi

    for instance in $instances; do
        tag_instance $instance;
    done

    wait
}

main "$@";
