#!/bin/sh

# AWS Tool
#
# Talks to the Amazon query API, see docs at:
# http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/query-apis.html
# if 
#   TMNAME is set in the environment, it contacts Amazon Endpoint of region where TM resides 
# else 
#  Endpoint of Local TM's regions 
#
#
# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/..
    cd ..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    fi
fi

if [ ! -z "$ZEUSHOME" ]
then
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -x $0 ${1+"$@"}

#!perl -w
#line 37

#-----------------------------------------------------------------------------#
# Start of perl code - Check environment
#-----------------------------------------------------------------------------#

BEGIN { unshift @INC, "$ENV{ZEUSHOME}/zxtm/lib/perl",
     "$ENV{ZEUSHOME}/zxtmadmin/lib/perl", "$ENV{ZEUSHOME}/perl" }

use strict;
use Zeus::TimeLocal qw( timegm );

use Zeus::ZXTM::EC2::EC2Utils qw( getIAMCredentials );
use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::LocationUtils qw( locationKey );
use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::NetworkingUtils qw( HostToAddr );
use Zeus::ZXTM::EC2::EC2Metadata qw( GetIPv4Associations
                                     GetAllMacsFromMetadata );
use Zeus::Execute qw( execute );
use POSIX qw( strftime );
use XML::Twig;

sub isInstanceInVPC( $$); 
sub convert_instance_response($);

#Amazon Query API version
my $API_VERSION="2013-10-15";

sub usage(;$)
{
   my( $fh ) = @_;
   $fh ||= *STDOUT;

   print $fh "Usage: awstool command <args>\n\n";
   print $fh "Tool that talks to the Amazon EC2 query API.\n";
}

if( ! @ARGV ) {
   usage( *STDERR );
   exit 1;
} elsif( grep /^--?h(elp)?$/, @ARGV ) {
   usage( *STDOUT );
   exit 0;
}

# Ensure ZEUSHOME is setup to point to our installation
if( ! $ENV{ZEUSHOME} || ! -d "$ENV{ZEUSHOME}/zxtm" ) {
    print STDERR "FATAL: \$ZEUSHOME is not set, or is set incorrectly\n"
               . "It should point to the Stingray installation\n";
    exit 1;
}

my $zeushome = $ENV{ZEUSHOME};

# Report an error
sub error( $$ )
{
   my( $tag, $error ) = @_;
   chomp( $tag, $error );

   # Report the error then add it with a time stamp to the end of the file
   print STDERR "$tag\t$error\n";
}

#-----------------------------------------------------------------------------#
# Important definitions
#-----------------------------------------------------------------------------#

my $hmacsum     = "$zeushome/zxtm/bin/hmacsum";
my $httpclient  = "$zeushome/admin/bin/httpclient";
my $aws_timeout = 10;  # timeout in seconds for contacting the AWS server

# We store ec2endpoint so we don't have to work it out every time
my $ec2endpointcache = "$zeushome/zxtm/internal/ec2endpoint";

# Some commands don't require an access key to work
my %no_access_key = ( 'check-keys' => 1, 'cluster-ips' => 1, 'current' => 1, 
                      'vpc-eip-associations' => 1,
                      'all-ipv4-associations'=> 1 );

my $storage = new Zeus::ZXTM::StorageManager();


#-----------------------------------------------------------------------------#
# Load EC2 settings - AWS server and access keys
#-----------------------------------------------------------------------------#

sub processQueryServer($)
{
   my( $query_server ) = @_;
   my( $awsProtocol, $awsServer, $awsPath ) = ( '', '', '' );

   if( $query_server =~ /(https?:\/\/)([^\/]+)(\/.*)?/ ) {
      $awsProtocol = $1;
      $awsServer = $2;
      $awsPath = $3 || '/';
   }

   return ( $awsProtocol, $awsServer, $awsPath );
}

# If we don't have an endpoint, try to find by looking at the availability zone
# from the metadata server and matching it to the aws endpoints returned by 
# DescribeRegions (strings aren't exact match so some educated assumptiond are 
# involved)
sub findEndpoint($$;$$) {
   my( $accessKeyId, $secretAccessKey, $securityToken, $machine ) = @_;

   # Check endpoint cache
   my $machine_name = defined( $machine ) ? ".$machine" : '';
   my $machine_endpoint_cache = "$ec2endpointcache$machine_name";

   if( open CACHE, $machine_endpoint_cache ) {
      while( <CACHE> ) {
         if( /^ec2!query_server\s+(.*)?/ ) {
            close CACHE;
            return $1;
         }
      }
      close CACHE;
   }
   
   # Get region descriptions (contains AWS query server urls for each region)
   $aws_timeout = 5;
   my $aws_server = 
      { 
         aws_protocol => "https://", aws_server => "ec2.amazonaws.com", aws_path => "/",
         access_key => $accessKeyId, secret_key => $secretAccessKey,
         security_token => $securityToken
      };
   my $request = makeRequest( $aws_server, "Action=DescribeRegions" );

   my $response = doRequest( $request, $aws_server );
   $response =~ s/\s+/ /g;

   if( $response !~ /<DescribeRegionsResponse/ ) {
      error( "INVALID_RESPONSE", "Could not determine AWS query servers.\n" );
      exit 1;
   }
   
   # Get the availability zone from the zxtm config (should be configured on
   # first boot)
   my $zxtm_cfg = $machine ? $storage->getZXTMConfig( $machine ) : $storage->getGlobalConfig();
   my $availabilityzone = $zxtm_cfg->get( 'ec2!availability_zone' );
   
   # Fallback to query request if looking up local machine
   if( !defined( $availabilityzone ) && !$machine ) {
      $availabilityzone = `$zeushome/zxtm/bin/ec2-interfaces metaquery placement/availability-zone 2>&1`;
      chomp( $availabilityzone );
   }

   if( ! defined( $availabilityzone ) || $availabilityzone =~ /^\s*$/ ) {
      error( "INVALID_RESPONSE", "Could not determine local availability zone.\n" );
      exit 1;
   }
   
   # Match machines availability zone to endpoints from AWS
   my $endpoint = undef;
   if( $response =~ /<regionInfo>(.*)<\/regionInfo>/ ) {
      my $items = $1;
      foreach my $item ( split /<\/item>/, $items ) {
         my( $region, $region_endpoint ) = ( undef, '' );
         $region   = $1 if( $item =~ /<regionName>(.*)<\/regionName>/ );
         $region_endpoint = $1 if( $item =~ /<regionEndpoint>(.*)<\/regionEndpoint>/ );  

         if( $region && $region_endpoint ) {
            if( $availabilityzone =~ /$region/ ) {
               $endpoint = "https://$region_endpoint/";
               last;
            } else {
               $endpoint = undef;
            }
         }
      }
   }
   
   # Store in cache
   if( $endpoint ) {
      open( CACHE, '>', $machine_endpoint_cache );  
      print CACHE "ec2!query_server\t$endpoint\n";
      close CACHE;
   }

   return $endpoint;
}

sub getEC2Settings(;$$$$$)
{
   my( $machine, $accessKeyId, $secretAccessKey, $query_server, $verify_server ) = @_;
   my $securityToken;

   my $zxtm_cfg = $machine ? $storage->getZXTMConfig( $machine ) : $storage->getGlobalConfig();
   my $location = $zxtm_cfg->get( 'location' );
   $location = '' unless( defined $location );

   $storage->setFallbackLocation( '' ) if( $location ne '' );

   my( $awsProtocol, $awsServer, $awsPath ) = ( '', '', '' );

   # Check configured keys in settings
   my $settings = $storage->getSettingsConfig();
   my $cas = undef;
   if( $settings ) {
      # Only get the access key from settings if we haven't been given one already
      if( ! $accessKeyId ) {
         $accessKeyId = $settings->get( locationKey( 'ec2!access_key_id', $location ), 1 );
         $secretAccessKey = $settings->get( locationKey( 'ec2!secret_access_key', $location ), 1 );
      }

      if( !$query_server ) {
         $query_server = $settings->get( locationKey( 'ec2!query_server', $location ) );
      }

      if( !defined( $verify_server ) ) {
         $verify_server = $settings->get( locationKey( 'ec2!verify_query_server_cert', $location ) );
      }
      if( !defined( $verify_server ) || ( $verify_server =~/^N/i ) ) {
         $verify_server = '';
      } elsif( $verify_server =~/^Y/i ) {
         $cas = "$ENV{ZEUSHOME}/zxtm/conf/ssl/cas";
      }
   }

   # If we have no credentials, use IAM role
   if( !$accessKeyId && !$secretAccessKey ) {
      my $iam_credentials = getIAMCredentials();
      if( defined( $iam_credentials ) ) {
         $accessKeyId = $iam_credentials->{access_key};
         $secretAccessKey = $iam_credentials->{secret_key};
         $securityToken = $iam_credentials->{security_token};
      }
   }

   if( $query_server ) {
      ( $awsProtocol, $awsServer, $awsPath ) = processQueryServer( $query_server );
   }

   # Check for cached value if in local location
   if( !$awsServer && $accessKeyId && $secretAccessKey ) { 
      my $endpoint = findEndpoint( $accessKeyId, $secretAccessKey, $securityToken, $machine );
      if( $endpoint ) {
         ( $awsProtocol, $awsServer, $awsPath ) = processQueryServer( $endpoint );
      }
   }

   return (
      access_key => $accessKeyId,       secret_key => $secretAccessKey,
      security_token => $securityToken,
      aws_protocol => $awsProtocol,     aws_server => $awsServer, 
      aws_path => $awsPath,
      aws_cas => $cas
   );
}


my( $ec2_key, $ec2_secret );
my( $clouduser ) = grep /--cloudcreds=/, @ARGV;
if( $ARGV[0] ne 'cluster-ips' &&
    defined $clouduser && $clouduser =~ /--cloudcreds=(.+)/ ) {
   $clouduser = $1;
   my $cc_conf = $storage->getCloudCredConfig( $clouduser );
   if( $cc_conf ) {
      my $zxtm_cfg = $storage->getGlobalConfig();
      my $location = $zxtm_cfg->get( 'location' );
      $location = '' unless( defined $location );
      # set up access details according to cc config
      $ec2_key = $cc_conf->get( locationKey( 'cred1', $location ), 1 );
      $ec2_secret = $cc_conf->get( locationKey( 'cred2', $location ), 1 );
   }
}

my %local_aws = ($ARGV[0] eq 'cluster-ips') ? () : getEC2Settings( $ENV{TMNAME}, $ec2_key, $ec2_secret );

# Last resort - if we still don't have an AWS endpoint, fall back 
# to using the default one
if ( ! $local_aws{aws_server} ) { 
   $local_aws{aws_protocol} = "https://";
   $local_aws{aws_server}   = "ec2.amazonaws.com";
   $local_aws{aws_path}     = "/";
}

# If we are not using the current command check the access keys are set
unless( $no_access_key{ $ARGV[0] } ) {
   if( !defined( $local_aws{access_key} ) || $local_aws{access_key} eq '' ) {
      error( "ACCOUNT_INVALID", "AWS Access Key ID is not set\n" );
      exit 1;
   }

   if( !defined( $local_aws{secret_key} ) || $local_aws{secret_key} eq '' ) {
      error( "ACCOUNT_INVALID", "AWS Secret Access Key is not set\n" );
      exit 1;
   }
}

#-----------------------------------------------------------------------------#
# Main functions for AWS queries
#-----------------------------------------------------------------------------#

sub getErrorMessage( $ )
{
   my ( $response ) = @_;

   $response =~ /<Error>.*<Message>(.+)<\/Message>.*<\/Error>/;
   return $1;
}

sub urlEncode( $ )
{
   my ( $string ) = @_;

   $string =~ s/([^A-Za-z0-9\~\-\_\.])/sprintf("%%%02X", ord($1))/seg;
   return $string;
}


sub awsSignature( $$$ )
{
   my ( $accessKeyId, $secretAccessKey, $msg ) = @_;

   my( $keyfile, $msgfile ) = ( "$zeushome/zxtm/internal/awskey-$$", "$zeushome/zxtm/internal/awsmessage-$$" );

   system( "touch $keyfile" );
   chmod( 0600, $keyfile );
   open( KEY, ">> $keyfile" );
   print KEY $secretAccessKey;
   close( KEY ); 

   system( "touch $msgfile" );
   chmod( 0600, $msgfile );
   open( MSG, ">> $msgfile" );
   print MSG $msg;
   close( MSG );

   my $signature = `$hmacsum --secretfile=$keyfile --sha256 $msgfile`;
   unlink $keyfile;
   unlink $msgfile;

   chomp( $signature );
   $signature = urlEncode( $signature );
    
   return $signature;
}

# Make request using signature version 2
sub makeRequest( $$@ )
{
   my ( $server, $action, @params ) = @_;

   my $access_key = $server->{access_key};
   my $secret_key = $server->{secret_key};
   my $security_token = $server->{security_token};

   my @standard_params = ( "AWSAccessKeyId=" . $access_key,
                           "SignatureMethod=HmacSHA256",
                           "SignatureVersion=2" );
   if( $security_token ) {
      push( @standard_params, "SecurityToken=" . urlEncode( $security_token ) );
   }

   # Add Expires (The date and time when the request signature expires, 
   # expressed in the format YYYY-MM-DDThh:mm:ssZ, as specified in the 
   # ISO 8601 standard.
   my $t = time() + 10;
   my @expires = gmtime( $t );
   my $expires_str = strftime( "%Y-%m-%dT%H%%3A%M%%3A%SZ", @expires );
   push( @standard_params, "Expires=$expires_str" );

   if( ! grep( /^Version=/, @params ) ) {
      push @standard_params, "Version=$API_VERSION";
   }

   my @p = sort { $a cmp $b } ( @standard_params, $action, @params );
   my $args = join( "&", @p );

   my $msg = "GET\n"
           . "$server->{aws_server}\n"
           . "$server->{aws_path}\n"
           . $args;

   my $signature = awsSignature( $access_key, $secret_key, $msg );

   my $request = "$server->{aws_protocol}$server->{aws_server}$server->{aws_path}?"
               . "$action&"
               . join( "&", sort{ $a cmp $b} 
               ( @standard_params, @params, "Signature=$signature" ) );

   return $request;
}

sub associateAddress( $$$;$$ )
{
   my ( $server, $publicIp, $instanceId, $privIp, $netiface ) = @_;
   my $request;
 
   # Get allocation ID which will indicate if EIP is
   # VPC or Standard EC2 EIP
   my $allocId = getEIPAllocationId( $server, $publicIp );

   # Check is Instance is a VPC instance
   if( isInstanceInVPC( $server, $instanceId ) ) {
      if ( !defined( $allocId ) ) {
         error("EIP_INSTANCE_MISMATCH", 
               "Elastic IP $publicIp cannot be used with VPC instance");
         exit(1);
      }

      if ( !$privIp ) {
         error("INVALID_PRIVATEIP", 
               "No private IP address specified");
         exit(1);
        
      }
      $request = makeRequest( $server,
                              "Action=AssociateAddress",
                              #"InstanceId=$instanceId", # No need to specify Instance ID
                              "AllocationId=$allocId",
                              "PrivateIpAddress=$privIp",
                              "NetworkInterfaceId=$netiface",
                              "AllowReassociation=true"

                           );
   } else {
      if ( defined( $allocId ) ) {
         error("EIP_INSTANCE_MISMATCH", 
               "Elastic IP $publicIp can only be used with VPC instances");
         exit(1);
      }

      $request = makeRequest( $server, 
                              "Action=AssociateAddress", 
                              "InstanceId=$instanceId",
                              "PublicIp=$publicIp" );
   }                          

   return $request;
}


sub disassociateAddress( $$$ )
{
   my ( $server, $publicIp, $instanceId ) = @_;
   my $request = undef;

   my $eipdata = getEIPAddressData( $server, $publicIp );
   if( defined( $eipdata->{instanceId} ) 
       && ( $eipdata->{instanceId} ne $instanceId ) ) {
      # EIP is not associated to the given instance 
      exit( 0 );
   }
   if ( defined( $eipdata->{'domain'} ) 
        && ( $eipdata->{'domain'} =~ /vpc/ ))
   {
      # Address is VPC EIP
      my $assocId = $eipdata->{'associationId'};
      if ($assocId ) {
         $request = makeRequest( $server, 
                              "Action=DisassociateAddress", 
                              "AssociationId=$assocId" );
      } else {
         # Exit as EIP doesn't seem to be associated wih any instance
         exit(0);
      }
   } else {
      $request = makeRequest( $server, 
                              "Action=DisassociateAddress", 
                              "PublicIp=$publicIp" );
   }
   return $request;
}


sub describeAddresses( $ )
{
   my ( $server ) = @_;

   my $request = makeRequest( $server, "Action=DescribeAddresses");
   return $request;
}

sub describeInstances( $;$ )
{
   my ( $server, $instanceId ) = @_;
   my @params = ();

   if ( $instanceId ) {
     push( @params, "InstanceId.0=$instanceId");
   }

   my $request = makeRequest( $server, "Action=DescribeInstances", @params );
   return $request;
}

sub describeRegions( $ )
{
    my ( $server ) = @_;
    my $request = makeRequest( $server, "Action=DescribeRegions");
    return $request;
}

sub allocateAddress( $;$ )
{
    my ( $server, $domain ) = @_;
    my @params = ();
    # By default allocate EC2 EIP
    $domain = $domain || 'standard';
    push( @params, "Domain=$domain" );

    my $request = makeRequest( $server, "Action=AllocateAddress", @params );
    return $request;    
}

sub releaseAddress( $$ )
{
   my ( $server, $publicIp ) = @_;

   my @params = ();

   my $allocId = getEIPAllocationId( $server, $publicIp );
   if ( $allocId ) {
      push (@params, "AllocationId=$allocId");
   } else {
      push( @params, "PublicIp=$publicIp");
   }
   
   my $request = makeRequest( $server, 
                              "Action=ReleaseAddress", 
                              @params );
   return $request;
}


sub checkEIPOwnership($$)
{
   my ( $server, $publicIp ) = @_;
   
   my $eips = doRequest( describeAddresses( $server ), $server );
   if( $eips !~ /<publicIp>\Q$publicIp\E<\/publicIp>/ ) {
      error( "NOT_OUR_EIP", "This Elastic IP is not associated with this account." );
      exit 1
   }
}


sub getResponseBody( $ ) {
    my ( $response ) = @_;

    $response =~ /^.+\r\n\r\n(.+)$/s;
    return $1;
}

sub get( $$ )
{
   my ( $request, $server ) = @_;

   
   my $cas = $server->{aws_cas};
   my @cmd = ( $httpclient, '-4', '-t', $aws_timeout );
   if( $cas ) {
      push( @cmd, "--verify", 
                  "--CA=$cas" );
   }
   push( @cmd, $request );
  
   my( $code, $response, $err ) = execute( \@cmd );

   if ( $code ) {
      error( "HTTP_ERROR", "Error whilst connecting to EC2 query server: $response$err\n" );
      exit 1;
   }

   return $response;
}


# doRequest( $request, $server, $continue_on_error, $continue_on_error_str_ref )
# Performs HTTP request. Calls exit(1) if request fails unless
# $continue_on_error is set. 
sub doRequest( $$;$$ )
{
   my ( $request, $server, $continue_on_error, $continue_on_error_str_ref ) = @_;

   my $response = get( $request, $server );

   if ( ! ( $response =~ /^HTTP\/1.1 200 OK.+$/s ) ) {
      if( !$continue_on_error ) {
         my $message = getErrorMessage( getResponseBody( $response ) );
         error( "AWS_ERROR", "$message\n" );
         exit 1;
      } else {
         #Set the string so that calling functions can read the error
         if( $continue_on_error_str_ref 
             && ( ref( $continue_on_error_str_ref ) eq 'SCALAR' ) ) {
             $$continue_on_error_str_ref = $response; 
         }
         return '';
      }
   }

   return getResponseBody( $response );
}

my %instance_id_cache;

sub getInstanceID(;$)
{
   my( $machine ) = @_;

   $machine ||= GetServerName();

   return $instance_id_cache{$machine} if( exists $instance_id_cache{$machine} );
      
   my $global_cfg = $storage->getZXTMConfig( $machine );
   if( $global_cfg ) {
      my $instance = $global_cfg->get( 'ec2!instanceid' );
      if( $instance ) {
         $instance_id_cache{$machine} = $instance;
         return $instance;
      }
   } 

   if( $machine eq GetServerName() ) {
      my $instance = `$zeushome/zxtm/bin/ec2-interfaces metaquery instance-id 2>&1`;
      chomp( $instance );
      if( $instance ) {
         $instance_id_cache{$machine} = $instance;
         return $instance;
      }
   }

   return undef;
}

# Returns hash of instances  and arrays of their associated Elastic IPs
# ( 
#     'i-xyzabc' => [10.01.1.100],
#     'i-rstabc' => [10.0.0.200, 10.4.8.1],
#  )

sub getEIPs($;$)
{
   my( $server, $no_err ) = @_;

   my $eips_xml = '';
   $eips_xml = doRequest( describeAddresses( $server ), $server, $no_err );
 
   $eips_xml =~ s/\s+/ /g;

   my %eips;

   # Work out which instances have EIPs, and if the IP the meta-data server 
   # returned is an EIP.
   if( $eips_xml =~ /<addressesSet/ ) {
      if( $eips_xml =~ /<addressesSet>(.*)<\/addressesSet>/ ) { 
         my $items = $1;
         foreach my $item ( split /<\/item>/, $items ) {
            my( $address, $instance ) = ( undef, '' );
            $address = $1 if( $item =~ /<publicIp>(.*)<\/publicIp>/ );
            $instance = $1 if( $item =~ /<instanceId>(.*)<\/instanceId>/ );

            if( $address && $instance ) {
               if ( !defined( $eips{$instance} ) ) {
                  $eips{$instance} = [];
                  
               }
               push( @{$eips{$instance}}, $address );
            }
         }
      }
   } 

   return %eips;
}

# A more safe way of getting the public IP address of the local machine. Uses
# the metaquery server but also checks the describe-addresses call to verify 
# that the current IP isn't an EIP assigned to another machine. If invalid account 
# settings are set we just use the metadata server.
sub getCurrentIP($)
{
   my( $server ) = @_;

   # What does the query API think we have as a public IP?
   my $query_ip = `$zeushome/zxtm/bin/ec2-interfaces get_publicip_from_meta 2>&1`;
   $query_ip = undef if( $? != 0 );

   my %new_eips;
   if( $server->{access_key} && $server->{secret_key} ) {
      %new_eips = getEIPs( $server, 1 );
   } else {
     # No credentials specified
     print $query_ip;
     exit 0; 
   }

   #Check if IP is eip
   my $query_is_eip = 0;
   if ( $query_ip ) {
      foreach my $inst ( keys( %new_eips ) ) {
         my @inst_eips = @{$new_eips{$inst}}; 

         if( grep( { $_ eq $query_ip } @inst_eips  ) ) {
            $query_is_eip = 1;
            last;
         }
      }
   }

   # We have an IP from the meta-data server, and it isn't an elastic IP. Its 
   # fine as it can be a public IP for EC2-Classic instance or Ephemeral 
   # IP for VPC instance
   if( $query_ip && !$query_is_eip ) {
      print $query_ip;
      exit 0;
   }

   # Get instance id from global.cfg
   my $instance_id = getInstanceID();

   # This instance has an EIP
   if( $new_eips{$instance_id} ) {
      my $eip = $query_ip;

      if( $query_ip && ( grep( { $_ eq $query_ip } @{ $new_eips{$instance_id} } ) ) ) {
         # If Query IP is present in the list, print that.
         print $eip;

      } else {
         # Else print whatever is the first I appeared in the list
         print( $new_eips{$instance_id}->[0] );

      }

      exit 0;
   }
   
   # Either we can't contact anything, or the meta-data server returned an EIP 
   # thats on another box (naughty EC2), return an error.
   error( "NO_EXT_IP", "Did not get valid response from metadata API.\n" );
   exit 1;
}


# A more safe way of getting the EIP associations of the local machine. Uses
# the metaquery server but also checks the describe-addresses call to verify 
# that the current IP isn't an EIP assigned to another machine. If invalid account 
# settings are set we just use the metadata server.
# It returns output in same format as get_eip_associations in ec2-interface
#           "<PrivateIP> <EIP> primary"
#           "<PrivateIP> 0 secondary" 
#           "<PrivateIP> <EIP> secondary" 
sub getVPCEIPAssociations( $ ) {
   my ($server) = @_;
   # What does the query API think we have as a public IP?
   my( $code, $out, $err ) = execute( [ "$zeushome/zxtm/bin/ec2-interfaces",
                                       "get_eip_associations" ] );
   if( $code ) {
      error("EC2_INTERFACE_ERROR", "$out$err" );
      exit( 1 );
   }

   my %new_eips;
   if( $server->{access_key} && $server->{secret_key} ) {
      %new_eips = getEIPs( $server, 1 );
   } else {
      print $out;
      exit( 0 );
   }
   
   # Separate each line 
   my @lines = split('\n', $out);
   my $qeips = {};
   # To preserve the order store private ips in array
   my @privips = ();
   my $check_eip = 0; # Validate EIP
   foreach my $line ( @lines ) {
      my ($priv, $eip, $type) = split('\s+', $line);
      push( @privips, $priv );
      $qeips->{$priv}->{'eip'}  = $eip;
      $qeips->{$priv}->{'type'} = $type;
      if( $eip ) {
         # Qip is a valid IP. 
         $check_eip = 1;
      }
   }

   if( !$check_eip ) {
      print $out;
      exit(0);
   }

   # Get instance id from global.cfg
   my $instance_id = getInstanceID();
   my $public_ip = undef;
   my $xml = doRequest( makeRequest( $server, "Action=DescribeInstances",
                                              "Version=$API_VERSION",
                                              "InstanceId.0=$instance_id" ),
                        $server );
   if( defined( $xml ) && ( 0 != length( $xml ) ) ) {
      my $data;
      ( undef, $data ) = convert_instance_response( $xml );
      if( $data 
          && $data->{$instance_id} ) {
             $public_ip = $data->{$instance_id}->{'public_ip'};
      }
   }

   # This instance has an EIP
   if( $new_eips{$instance_id} ) {
      #Validate the hash we got using metadata server against
      # data returned by API server
      foreach my $pip ( keys %$qeips ) {
         my $qip = $qeips->{$pip}->{'eip'};
         
         if( $qip ) {
            if( $public_ip && ( $qip eq $public_ip ) ) {
                # It's returned as public IP from Endpoint server
                # so must be valid. 
               next;
            } 
            if( !grep( { $_ eq $qip } @{ $new_eips{$instance_id} } ) ) {
               # Not a valid entry. change it to 0
               $qeips->{$pip}->{'eip'} = "0";
            }
         }
      }
   } else {
      # instance has no EIP, delete all EIPs except what's returned as public ip
      # as that might not be an EIP but ephemeral public IP
      foreach my $pip ( keys %$qeips ) {
         if( $public_ip && ( $qeips->{$pip}->{'eip'} eq $public_ip ) ) {
            next;
         }
         $qeips->{$pip}->{'eip'} = 0;
      }
   }

   #Now print the list in order we received from metadata server
   foreach my $pip ( @privips ) {
      print "$pip $qeips->{$pip}->{'eip'} $qeips->{$pip}->{'type'}\n";
   }
   exit(0);

}


sub getAllIPv4Associations
{
   my ($server) = @_;
   
   my @macs = GetAllMacsFromMetadata();
   if( !scalar( @macs ) ) {
      error( "EC2_INTERFACE_ERROR", "Failed to get List of ENIs" );
      exit( 1 );
   }
   
   my $macs_ip_assoc_map = {};
   my $check_eips = 0;
   my @map = ();
   foreach my $mac ( @macs ) {
      my @associations =  GetIPv4Associations( $mac );
      $macs_ip_assoc_map->{$mac} = \@associations;
      
      #Check if we need to verify eip
      if( !$check_eips ) {
         foreach my $assoc ( @{$macs_ip_assoc_map->{$mac}} ) {
            if( $assoc && ( $assoc ne "0.0.0.0" ) ) {
               $check_eips = 1;
            }
         }
      }      
   }
   
   #Function to print the output
   my $print_mac_info = sub {
      my $string;
      foreach my $mac ( @macs ) {
         $string .= "ipv4-associations#";
         $string .= "$mac=";
         foreach my $assoc ( @{$macs_ip_assoc_map->{$mac}} ) {
            my $pip = $assoc->[0];
            my $eip = $assoc->[1] || "0.0.0.0";
            $string .= $pip . ':' . $eip .',';
         }
         $string .= "\n";
      }
      #Remove last new line character
      chomp($string);
      
      print( "$string" );      
   };
   
                                         
   
   #Get List of EIPS
   my %new_eips;
   if( $check_eips && $server->{access_key} && $server->{secret_key} ) {
      %new_eips = getEIPs( $server, 1 );
   } else {
      # Access key is not set, print what we have got from
      # from metadata server 
      $print_mac_info->();
      exit( 0 );
   }   

   # Get instance id from global.cfg
   my $instance_id = getInstanceID();
   my $public_ip = undef;
   my $xml = doRequest( makeRequest( $server, "Action=DescribeInstances",
                                              "Version=$API_VERSION",
                                              "InstanceId.0=$instance_id" ),
                        $server );
   if( defined( $xml ) && ( 0 != length( $xml ) ) ) {
      my $data;
      ( undef, $data ) = convert_instance_response( $xml );
      if( $data 
          && $data->{$instance_id} ) {
             $public_ip = $data->{$instance_id}->{'public_ip'};
      }
   }
   # This instance has an EIP
   if( $new_eips{$instance_id} ) {
      #Validate the hash we got using metadata server against
      # data returned by API server
      foreach my $mac ( @macs ) {
         if( !$macs_ip_assoc_map->{$mac} ) {
            next;
         }
         foreach my $assocs ( @{$macs_ip_assoc_map->{$mac}} ) { 
            my $qip = $assocs->[1];
         
            if( $qip && $qip ne "0.0.0.0" ) {
               if( $public_ip && ( $qip eq $public_ip ) ) {
                   # It's returned as public IP from Endpoint server
                   # so must be valid. 
                  next;
               } 
               if( !grep( { $_ eq $qip } @{ $new_eips{$instance_id} } ) ) {
                  # Not a valid entry. change it to 0
                  $assocs->[1] = "0.0.0.0";
               }
            }
         }
      }
   } else {
      # instance has no EIP, delete all EIPs except what's returned as public ip
      # as that might not be an EIP but ephemeral public IP
      foreach my $mac (@macs ) {
         foreach my $assocs ( @{$macs_ip_assoc_map->{$mac}} ) { 
            if( $public_ip && ( $assocs->[1] eq $public_ip ) ) {
               next;
            }
            $assocs->[1] = "0.0.0.0";
         }
      }
   }

   #Now print the list in order we received from metadata server
   $print_mac_info->();
   exit(0);
}


# Check the key in the keyfile passed on the command line is valid by doing
# a test request to AWS.
sub checkKey()
{
   my $key_file = $ARGV[1] || '';
   unless( -f $key_file ) {
      error( "INTERNAL_ERROR", "Key file cannot be accessed.\n" );
      exit 1;
   }
   my $keys = `cat $key_file`;

   my( $accessKeyId, $secretAccessKey, $query_server, $verify_server ) = ( split( /\n/, $keys ) );
   my %server = getEC2Settings( undef, $accessKeyId, $secretAccessKey, $query_server, $verify_server );

   $aws_timeout = 5;
   my $response = doRequest( describeInstances( \%server ),
                             \%server );
   if( $response !~ /<DescribeInstancesResponse/ ) {
      error( "INVALID_RESPONSE", "Account verify failed, invalid response.\n" );
      exit 1;
   }
  
   my $instance = getInstanceID();
 
   if( $instance =~ /^[\w\-\.]+$/ && 
       $response !~ /<instanceId>$instance<\/instanceId>/ ) 
   {
      error( "NOT_THIS_INSTANCE", "The specified account does not manage this instance.\n" );
      exit 1;
   }

   exit 0;
}

sub checkClusterIPs()
{
   my( @mappings );
   
   # Get configs for each ZXTM
   foreach my $machine ( sort $storage->getAllZXTMNames() ) {
      my $conf = $storage->getZXTMConfig( $machine );
      next unless( $conf );

      my $instance_id = getInstanceID( $machine );
      next unless( $instance_id ); # Not an EC2 service, don't need to get 
                                   # its public ip

      my %ec2 = getEC2Settings( $machine );
      unless( $ec2{access_key} && $ec2{secret_key} ) {
         push( @mappings, "$machine\tNO_ACCESS_KEY" );
         next; 
      }

      # Work out public IP
      my $public_ip = 'UNKNOWN';

      # Get the public IP of instances in particular region
      # and store in cache for server
      my $instance_data;
      my $xml = doRequest( makeRequest( \%ec2, "Action=DescribeInstances",
                                               "Version=$API_VERSION",
                                               "InstanceId.0=$instance_id" ),
                            \%ec2 );
      if( !defined $xml || 0 == length( $xml ) ) {
      } else {
         ( undef, $instance_data ) = convert_instance_response( $xml );
      }

      if( $instance_data 
          && $instance_data->{$instance_id} ) {
         $public_ip = $instance_data->{$instance_id}->{'public_ip'};
      } else {
         $public_ip = 'NO_INSTANCE_DATA';
      }

      push( @mappings, "$machine\t$public_ip" );
   }
   
   print "OK\n";
   foreach my $mapping ( @mappings ) {
      print "$mapping\n";
   }
}

# getEIPAddressData
# Returns a hash containing all the info about
# and elastic IP as returned by DescribeAddresses.
# {
#     publicIp  => 107.21.16.146
#     allocationId => eipalloc-ca05bda
#     ...
# }
sub getEIPAddressData( $$ )
{
  my ( $server, $eip ) = @_;
  my $info = {};
  my $response = doRequest( describeAddresses( $server ), $server ); 
  $response =~ s/\s+/ /g;

   if( $response !~ /<DescribeAddressesResponse/ ) {
      error( "INVALID_RESPONSE", "Failed to get list of Elastic IP addresses\n" );
      exit 1;
   }
  
   if( $response =~ /<addressesSet>(.*)<\/addressesSet>/ ) { 
      my $addr_set = $1;
      foreach my $addr_data ( split( /<\/item>/i, $addr_set ) ) {
         if ( $addr_data =~ /<publicIp>$eip<\/publicIp>/i) {
            my @all_data = split( '\s+', $addr_data );
            foreach my $data ( @all_data ) {
               my ( $key, $value ) = ();
               ( $key, $value ) = $data =~ /<(.*)>(.*)</;
               if ( $key ) {
                  $info->{$key} = $value;
               }
            }
            last;
         }
      }
   }
   return $info; 
}

sub getEIPAllocationId( $$ )
{ 
   my ( $server, $publicIp ) = @_;
   my $eipdata = getEIPAddressData( $server, $publicIp );
   return $eipdata->{'allocationId'};
}
 
# Returns vpc id  
sub isInstanceInVPC( $$ )
{
   my ( $server, $instanceId ) = @_;
   my $vpcid = undef;
   my $response = doRequest( describeInstances( $server, $instanceId ), $server );
   $response =~ s/\s+/ /g;

   if( $response !~ /<DescribeInstancesResponse/ ) {
      error( "INVALID_RESPONSE", "Failed to get instance information\n" );
      exit 1;
   }

   ( $vpcid ) = $response =~ /<vpcId>(.*)?<\/vpcId>/;

   return $vpcid;
}


# Parses command line arguments and returns
# ( [ RunInstances arguments ], 
#    {  TagName => Value }
# )
sub parse_createnode_args($)
{
   my( $userargs ) = @_;
   my $result = [];
   my $createtags = {};
   my @security_group_ids = ();
   my ( $subnetid, $assoc_public_ip );

   foreach my $arg ( @$userargs ) {
      if( $arg =~ /^--imageid=(.+)/ ) {
         push @$result, "ImageId=$1";
      } elsif( $arg =~ /^--sizeid=(.+)/ ) {
         push @$result, "InstanceType=$1";
      } elsif ( $arg =~ /^--name=(.+)/ ) {
         my $name = $1;
         if( $name ) {
            $createtags->{'Name'} = $name;
         } 
      } elsif( $arg =~ /^--securitygroupids=(.+)/ ) {
        my $ids = $1;
        @security_group_ids = split( ',', $ids );
      } elsif( $arg =~ /^--subnetid=(.+)/ ) {
         $subnetid = $1;
      } elsif( $arg =~ /^--associatepublicip=(.+)/ ) {
        $assoc_public_ip = $1;
      } elsif( $arg =~ /^--extraargs=(.+)/ ) {
         # Comma separated list can come in which
         # will be passed in RunInstances API call
         my $extra = $1;
         my @extra_args = split( /\s*,\s*/, $extra );
         foreach my $ar ( @extra_args ) {
            # The value might be base64 encoded ending with '=' character(s),
            # so URL encode the value which comes after the first '='.
            if( $ar =~ /^(.+?)\s*=\s*(.+)$/ ) {
               my $value = urlEncode( $2 );
               push @$result, "$1=$value";
            }
         }
      } 
   }

   if( $subnetid ) {
      #Launch a node inside VPC

      # If user has asked to associate public IP to the instance in case of VPC instance
      # then parameters (security groups, subnetid) have to be associated 
      # to network interface.
      my $assoc_public_ip_flag = undef;
      if( $assoc_public_ip && $assoc_public_ip =~ /yes/i ) {
         $assoc_public_ip_flag = 1;
         push @$result, "NetworkInterface.0.AssociatePublicIpAddress=true";
         push @$result, "NetworkInterface.0.DeviceIndex=0";
      }

      my $index = 0;
      foreach my $sec_id ( @security_group_ids ) {
         if( $assoc_public_ip_flag ) {
             push @$result, "NetworkInterface.0.SecurityGroupId.$index=$sec_id";
         } else {
            push @$result, "SecurityGroupId.$index=$sec_id";
         }
         $index++; 
      }

      if( $assoc_public_ip_flag ) {
         push @$result, "NetworkInterface.0.SubnetId=$subnetid";
      } else {
         push @$result, "SubnetId=$subnetid";
      }
   } else {
      #Launch instance inside EC2-Classic. Add security group IDs
      my $index = 0;
      foreach my $sec_id ( @security_group_ids ) {
         push @$result, "SecurityGroupId.$index=$sec_id";
         $index++;
      }
   }

   return ( $result, $createtags );
}

sub create_node($@)
{
   my ( $server, @args ) = @_;
   
    my $return = "";
   # we always create one node at a time:
   my $version = "Version=$API_VERSION"; 
   my @queryargs = ( "MaxCount=1",
                     "MinCount=1", $version );
   my ( $userargs, $createtags ) = parse_createnode_args( \@args );

   if( !defined $userargs || ref $userargs ne 'ARRAY' || !scalar( @$userargs ) ) {
      # at the very least we need an ImageId from the user (size defaults
      # to m1.small on EC2)
      print STDERR "missing arguments for 'createnode'\n";
      exit 1;
   }
   push( @queryargs, @$userargs ); 

   my $createnode_resp = doRequest( makeRequest( $server, "Action=RunInstances", @queryargs ),
                        $server );
   if( !defined $createnode_resp || 0 == length( $createnode_resp ) ) {
      print STDERR "code\t500\n";
      return;
   } else {
      my ( $instanceid ) = $createnode_resp =~ /<instanceId>(.*)?<\/instanceId>/;
      my $append_tags = "";

      if( $createtags 
          && ( ref( $createtags ) eq 'HASH') 
          && scalar( keys( %$createtags ) ) ) {
          @queryargs = ( "ResourceId.0=$instanceid", $version ); 
         # Add some tags to the instance
         my @tags = ();
         my $index = 1;
         foreach my $tag ( keys( %$createtags ) ) {
            push( @tags, "Tag.$index.Key=$tag" );
            push( @tags, "Tag.$index.Value=$createtags->{$tag}" );
            $append_tags .= lc( $tag ) . "\t$createtags->{$tag}\n";
            $index++;
         }         
         if( scalar( @tags ) ) {
            my $error;
            push( @queryargs, @tags );
            my $createtags_resp = doRequest( makeRequest( $server, "Action=CreateTags", @queryargs ),
                                             $server, 1, \$error ); # doRequest continue_on_error =1 
                                                               # as we want to destroy the instance if
                                                               # CreateTags didn't work
            if( !defined $createtags_resp 
                || 0 == length( $createtags_resp ) 
                || $createtags_resp !~/<return>true<\/return>/ ) {
               #Destroy the instance and return
               my $xml = doRequest( makeRequest( $server, "Action=TerminateInstances", 
                                                              "InstanceId.0=$instanceid",
                                                              $version ),
                           $server );
               if( !defined $xml || 0 == length( $xml ) ) {
                  print STDERR "code\t500\n";
                  exit( 1 );
               } else {
                  #Successfully destroyed the instance
                  print STDERR "AWS_ERROR: Failed to add tags to the instance. Error is '$error'\n";
                  exit( 1 );
               }
            }
            # As we have successfully added the tags now Call DescribeInstances
            $error = 0;
            my $response = doRequest( describeInstances( $server, $instanceid ),
                                      $server, 1, \$error );
            if( !defined $response || 0 == length( $response ) ) {
               #If Describe Instance fails we can probably live with it 
               # and just return original create instance response and 
               # append the tags and values
               ( $return ) = convert_instance_response( $createnode_resp );
               $return .= $append_tags;
            } else {
               ( $return ) = convert_instance_response( $response );
            }
         }
      } else {
         # No Tags 
         ( $return ) = convert_instance_response( $createnode_resp );
            #warn( "3 $return ");
      }
      print "code\t202\n";
      print "$return";
   }
   return;
}

sub parse_destroynode_args($)
{
   my( $userargs ) = @_;
   my $result = [];
   foreach my $arg ( @$userargs ) {
      if( $arg =~ /^--id=(.+)/ ) {
         push @$result, "InstanceId.1=$1";
      }
   }
   return $result;
}

sub parseTagSet($$);
my %ALL_INSTANCES = ();

#Handler to parse instancesSet in XML data
sub parseInstancesSet
{
   my ( $twig, $i_sets ) = @_;
   my$statusstrings = {
                       pending => 'pending',# hrmgpf
                       running => 'active',
                       terminated => 'destroyed',
                       "shutting-down" => 'destroyed',
                       stopping => 'destroyed',
                       stopped => 'destroyed'
                       };
    my $need = { instanceId => 'uniq_id',
                imageId => 'imageid',
                instanceState => 'status',
                shutdownState => 'status', # in TerminateInstance response 
                                            # when version=2009-07-15
                currentState => 'status', # in TerminateInstance response 
                                          # when API version > 2012-10-01 
                instanceType => 'sizeid',
                privateIpAddress => 'private_ip',
                ipAddress => 'public_ip',
                launchTime => 'created',
                subnetId => 'subnet_id',
                tagSet => 'tagset',
              };
   my $instance = $i_sets->first_child();
   while( $instance ) {
       my $xml_str = $instance->xml_string() ;
       #print( "XML String - '$xml_str'\n");
       my $instanceid = $instance->children_text( 'instanceId' );
       my $node = {};
       #Also store which key in node mapped to which XML element
       #as keys in %need can map to same value e.g status
       my $node_to_xml_key = {}; 
       while( my( $k, $v ) = each %$need ) {
            if( exists( $node->{$v} ) 
                && ( $node->{$v} ne 'unknown' ) ) {
               # $v is already set, don't overwrite.
               next;
            }   
            my $text = $instance->children_text( $k );
            $node_to_xml_key->{$v} = $k;
            if( $text ) {
               $node->{$v} = $text;
        #       print( "Store $v => $text \n");
            } elsif( !exists $node->{$v} ) {
               $node->{$v} = 'unknown';
        #       print( "Store $v => unknown \n");
            }
        }

         # special massage for a few keys:
         # 1) convert xsd:dateTime to time_t
         if( defined $node->{created} &&
             $node->{created} =~
             m|(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.\d+Z| ) {
            $node->{created} =
                Zeus::TimeLocal::timegm( $6, $5, $4, $3, $2-1, $1-1900 );
         } else {
            $node->{created} = 0;
         }

         # 2) map status string
         #print( "'$node->{status}' \n");
         if( $node->{status} ) {  
            #print( "status = $node->{status}\n");    
            my $status = $instance->first_child( $node_to_xml_key->{'status'} );
            #print( "Value of $node_to_xml_key->{'status'} " , $status->xml_string(), "\n" );
            my $name = $status->children_text('name');
            #print( "$instanceid , Status =  $name \n");
            if( defined $statusstrings->{$name} ) {
               $node->{status} = $statusstrings->{$name};
            }
         } else {
            $node->{status} = 'unknown';
         }
         # 3)Fetch required data from tag set and delete it once done.
         #   Deleting to avoid passing xml (which won't be of any use) 
         #   in the nodes hash to the calling function.
         if( $node->{tagset} && ( $node->{tagset} ne 'unknown' ) ) {
            parseTagSet( $instance->first_child( $node_to_xml_key->{tagset} ),
                      $node );
         }
         delete( $node->{tagset} );
        
         # Sort out IPs
         if( !defined( $node->{private_ip} ) ||
             $node->{private_ip} eq 'unknown' ) {
            $node->{private_ip} = '0.0.0.0'; # IPv4 wildcard
         }
         if( !defined( $node->{public_ip} ) ||
             $node->{public_ip} eq 'unknown' ) {
            $node->{public_ip} = '0.0.0.0'; # IPv4 wildcard
         }

         $ALL_INSTANCES{$instanceid} = $node;
     
       $instance = $instance->next_sibling();

   }
   $twig->purge();
}

# Returns string using ALL_INSTANCES hash in format as expected
# by autoscaler.
sub instances_data_string()
{
#  String in format 
#        node
#        created 1378725871
#        sizeid  m1.small
#        uniq_id i-7386433c
#        status  destroyed
#        public_ip       0.0.0.0
#        private_ip      10.0.0.12
#        imageid ami-8d1109f9
#        subnet_id subnet-dfdfgkgl
#        node
#        created 1375266475
#        sizeid  m1.small
#        uniq_id i-25d8176b
#        status  active
#        public_ip       54.228.58.140
#        private_ip      10.62.250.197
#        imageid ami-79fafd0d

   my $result = "";
   foreach my $instanceid ( keys( %ALL_INSTANCES ) ) {
      
      $result .= "node\n";
      my $instance = $ALL_INSTANCES{$instanceid};
      while(  my ($k, $v ) = each ( %$instance ) ) {
         $result .= "$k\t$v\n";
      }
   } 
   return $result;
}

sub parseTagSet($$)
{
   my ( $tagset_elt, $node_ref ) = @_;
   # Tags which we are interested in
   # They may or may not be present
   my $tags = { 'Name' => 'name'};
   my $child = $tagset_elt->first_child();
   while( $child ) {
      my $key = $child->children_text( 'key' );
      my $value = $child->children_text( 'value' );
      if( exists( $tags->{ $key } ) ) {
         $node_ref->{ $tags->{$key} } = $value;
      }
      $child = $child->next_sibling();
   }
}

# Parses XML response as returned
# by DescribeInstances or RunInstances or TerminateInstances
# Returns (String, hash of all instances)
sub convert_instance_response($)
{
   my( $xml ) = @_;

   %ALL_INSTANCES = (); # This is global which will be modified
                        # by parseInstanceSets
   my $twig= new XML::Twig( 
                   twig_handlers =>
                          { instancesSet => \&parseInstancesSet }
             );
             
   my $ret_twig = $twig->safe_parse( $xml );
   if( !$ret_twig ) {
      # Parsing failed.
      return "";
   }
   
   return ( instances_data_string(), \%ALL_INSTANCES );
}

# VPC Only command
# Assign a secondary private IP address to given the network interface
# If IP is not specified, Amazon assigns an IP itself using dhcp
sub assignSecondaryPrivateIPAddress($$;$)
{
   my ( $server, $netiface, $ip ) = @_; 
   my @params = ( "NetworkInterfaceId=$netiface");
   if( $ip ) {
     push(@params,  "PrivateIpAddress.0=$ip");
   } else {
     # IP will be assigned automatically by Amazon
     push(@params,  "SecondaryPrivateIpAddressCount=1");
   }
   my $request = makeRequest( $server, "Action=AssignPrivateIpAddresses", @params );
   return $request; 
}


# VPC Only command
# Unassign a secondary private IP address to the given network interface
sub unassignSecondaryPrivateIPAddress($$$)
{
   my ( $server, $netiface, $ip ) = @_; 
   my @params = ( "NetworkInterfaceId=$netiface",
                  "PrivateIpAddress.0=$ip");
   my $request = makeRequest( $server, "Action=UnassignPrivateIpAddresses", @params );
   return $request; 
}

sub describeNetworkInterface( $$ ) 
{
   my ( $server, $netid ) = @_;
   my @params = ();
   if ($netid ) {
      push( @params, "NetworkInterfaceId.0=$netid" );
   }
   my $request = makeRequest( $server, "Action=DescribeNetworkInterfaces", @params );
   return $request; 
} 

#-----------------------------------------------------------------------------#
# Interpret command arguments
#-----------------------------------------------------------------------------#


if ( $ARGV[0] eq "describe-addresses" ) {
   print doRequest( describeAddresses( \%local_aws ), \%local_aws );

} elsif ( $ARGV[0] eq "describe-instances" ) {
   print doRequest( describeInstances( \%local_aws, $ARGV[1] ),
                    \%local_aws );

} elsif ( $ARGV[0] eq "describe-regions" ) {
   print doRequest( describeRegions( \%local_aws ), \%local_aws );

} elsif ( $ARGV[0] eq "associate-address" ) {
   checkEIPOwnership( \%local_aws, $ARGV[1] );
   print doRequest( associateAddress( \%local_aws, $ARGV[1], $ARGV[2], $ARGV[3], $ARGV[4] ),
                    \%local_aws );

} elsif ( $ARGV[0] eq "disassociate-address" ) {
   checkEIPOwnership( \%local_aws, $ARGV[1] );
   print doRequest( disassociateAddress( \%local_aws, $ARGV[1], $ARGV[2] ),
                    \%local_aws);

} elsif ( $ARGV[0] eq "allocate-address" ) {
   print doRequest( allocateAddress( \%local_aws, $ARGV[1] ), \%local_aws );

} elsif ( $ARGV[0] eq "release-address" ) {
   print doRequest( releaseAddress( \%local_aws, $ARGV[1] ), \%local_aws );

} elsif ( $ARGV[0] eq "assign-secondary-private-address" ) {
   print doRequest( assignSecondaryPrivateIPAddress( \%local_aws, $ARGV[1], $ARGV[2] ),
                    \%local_aws );

} elsif ( $ARGV[0] eq "unassign-secondary-private-address" ) {
   print doRequest( unassignSecondaryPrivateIPAddress( \%local_aws, $ARGV[1], $ARGV[2] ),
                    \%local_aws );

} elsif ( $ARGV[0] eq "check-keys" ) {
   checkKey();
   
} elsif ( $ARGV[0] eq "endpoint" ) {
   $aws_timeout = 5;
   print findEndpoint( $local_aws{access_key}, $local_aws{secret_key}, $local_aws{security_token}, $ARGV[1] );

} elsif ( $ARGV[0] eq "current" ) {
   getCurrentIP( \%local_aws );

} elsif ( $ARGV[0] eq "cluster-ips" ) {
   checkClusterIPs();

} elsif ( $ARGV[0] eq "vpc-eip-associations" ) {
  getVPCEIPAssociations( \%local_aws );

} elsif ( $ARGV[0] eq "all-ipv4-associations" ) { 

# all-ipv4-associations     Prints in following format IPv4 associations of all ENIs attached to the instance
#                                    "ipv4-associations#<mac1>=<pip>:<eip>,<pip>:<eip>
#                                     ipv4-associations#<mac2>=<pip>:<eip>,<pip>:<eip>"
#                                     eip will be 0.0.0.0 when no Elastic IP associated to the private IP.
   getAllIPv4Associations( \%local_aws );
}
elsif ( $ARGV[0] eq "describe-networkinterfaces" ) {
  print doRequest( describeNetworkInterface( \%local_aws, $ARGV[1] ), \%local_aws );

} elsif( $ARGV[0] eq "status" ) {
   my $xml = doRequest( makeRequest( \%local_aws, "Action=DescribeInstances", "Version=$API_VERSION" ),
                        \%local_aws );
   if( !defined $xml || 0 == length( $xml ) ) {
      print STDERR "code\t500\n";
   } else {
      print "code\t200\n";
      my( $result, undef ) = convert_instance_response( $xml );
      print( $result );
   }
} elsif( $ARGV[0] eq "createnode" ) {

   shift @ARGV;
   create_node(\%local_aws, @ARGV );
} elsif( $ARGV[0] eq 'destroynode' ) {
   shift @ARGV;
   my @queryargs = ( "Version=$API_VERSION" );
   my $userargs = parse_destroynode_args(\@ARGV );
   # should be something like "InstanceId.1=i-3ea74257";
   if( !defined $userargs || ref $userargs ne 'ARRAY' || !scalar( @$userargs ) ) {
      # at the very least we the instanceId from the user
      print STDERR "missing argument '--id=' for 'destroynode'\n";
      exit 1;
   }
   push @queryargs, @$userargs;
   my $xml = doRequest( makeRequest( \%local_aws, "Action=TerminateInstances", @queryargs ),
                        \%local_aws );
   if( !defined $xml || 0 == length( $xml ) ) {
      print STDERR "code\t500\n";
   } else {
      print "code\t202\n";
      my ( $result ) = convert_instance_response( $xml );
      print $result;
   }
} else {
   print STDERR "Unrecognized operation: $ARGV[0]\n";
   exit 1;
}
