#!/bin/bash

ME=$(basename $0);

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


function _init ()
{
    ec2_placement_region=$1
    ec2_placement_availability_zone=$2
    piece_size=$3
    ec2_instance_id=$4
    arrdev=$5
}


function tag_ebs ()
{
    myname=$(ec2-describe-tags --region $ec2_placement_region -F key=Name | grep $ec2_instance_id | cut -f5 | head -n1);
    mynum=${myname##*-};
    ec2-create-tags --region $ec2_placement_region $volid \
        --tag Domain=$DOMAIN \
        --tag Device=${arrdev} \
        --tag Instance=$ec2_instance_id \
        --tag Name="vol-$DOMAIN-$mynum" >/dev/null 2>&1;
}


function attach_ebs ()
{
    volid=$(ec2-create-volume --region $ec2_placement_region -z $ec2_placement_availability_zone -s $piece_size | cut -f2);
    attvol=$(ec2-attach-volume --region $ec2_placement_region $volid -i $ec2_instance_id -d ${arrdev});

    tag_ebs;
}


function show_help()
{
    usage_banner;
    cat <<EOF

Usage:  $ME [-h] REGION ZONE PIECE_SIZE INSTANCE_ID DEVICE

Create new EBS volume and attach to the DEVICE.  REGION is Amazon
region, ZONE is Amazon zone, PIECE_SIZE is size of each piece,
INSTANCE_ID is instance id and DEVICE is the device which is used
to access EBS volume.

WARNING: This is an internal tool.  You should not invoke this
         directly.  Refer gluster-provision-storage tool for more
         detail.

Miscellaneous:
  -h                        display this help and exit

Example:
  $ME us-west us-west-1a 8 i-1234567 /dev/sdd
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 five non-option arguments.
    if [ $# -ne 5 ]; then
	show_help
	exit 1
    fi

    set -e

    _init "$@"

    attach_ebs
}


main "$@"
