#!/bin/sh

# AWS Tool
#
# Talks to the Amazon query API, see docs at:
# http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/query-apis.html
#

# 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 32

#-----------------------------------------------------------------------------#
# 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::ZXTM::ZXML qw( parseXML );
use Zeus::TimeLocal qw( timegm );

use Zeus::ZXTM::StorageManager;
use Zeus::ZXTM::LocationUtils qw( locationKey );
use Zeus::ZXTM::Utils qw( GetServerName );
use Zeus::NetworkingUtils qw( HostToAddr );
use Zeus::Execute qw( execute );

sub isInstanceInVPC( $$); 

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 );

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, $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 $request = makeRequest(
      { 
         aws_protocol => "https://", aws_server => "ec2.amazonaws.com", aws_path => "/",
         access_key => $accessKeyId, secret_key => $secretAccessKey
      },
      "Action=DescribeRegions"
   );

   my $response = doRequest( $request );
   $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 ) = @_;

   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();
   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 );
      }

      my $query_server = $settings->get( locationKey( 'ec2!query_server', $location ) );
      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, $machine );
      if( $endpoint ) {
         ( $awsProtocol, $awsServer, $awsPath ) = processQueryServer( $endpoint );
      }
   }

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


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( undef, $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 );   # do we need this or not?
    
   return $signature;
}

# Make request, specifying the AWS server 
sub makeRequest( $$@ )
{
   my ( $server, $action, @params ) = @_;

   my $timestamp = `date -u +%Y-%m-%dT%H%%3A%M%%3A%SZ`; # Pre-url-encoded
   chomp( $timestamp );

   my @standard_params = ( "AWSAccessKeyId=$server->{access_key}",
                           "SignatureMethod=HmacSHA256",
                           "SignatureVersion=2",
                           "Timestamp=$timestamp" );

   if( ! grep /^Version=/, @params ) {
      push @standard_params, "Version=2012-10-01";
   }

   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( $server->{access_key}, $server->{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 ) = @_;
   my $request = undef;

   my $eipdata = getEIPAddressData( $server, $publicIp );
   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 ) );
   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 ) = @_;

   my $response = `$httpclient -4 -t $aws_timeout \"$request\" 2>&1`;

   # Bail out early if we timed out or couldn't connect
   if ( $? != 0 ) {
      chomp( $response );
      error( "HTTP_ERROR", "Error whilst connecting to EC2 query server: $response\n" );
      exit 1;
   }

   return $response;
}


sub doRequest( $;$ )
{
   my ( $request, $continue_on_error ) = @_;

   my $response = get( $request );

   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 {
         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 ), $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;
         }
      }
   }

   # Check if instance is VPC
   my $zxtmcfg = $storage->getGlobalConfig();
   my $vpcid = $zxtmcfg->get("ec2!vpcid");

   # We have an IP from the meta-data server, and it isn't an elastic IP. Its 
   # probably fine for Non-VPC instances
   if( $query_ip && !$vpcid && !$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();

   # 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 && ( !grep( { $_ eq $qip } @{ $new_eips{$instance_id} } ) ) ) {
            # Not a valid entry. change it to 0
            $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);
   }
   
   error( "NO_EXT_IP", "Did not get valid response from metadata API.\n" );
   exit 1;

}

# 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 ) = ( split( /\n/, $keys ), '', '' );
   my %server = getEC2Settings( undef, $accessKeyId, $secretAccessKey );

   $aws_timeout = 5;
   my $response = doRequest( describeInstances( \%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, %eips_cache, %instance_cache );

   # 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; 
      }

      my $cache_key = join( ',', map { "$_:[$ec2{$_}]" } sort( keys %ec2 ) );
      
      # Get EIPs and store in cache for server
      unless( defined $eips_cache{$cache_key} ) {
         $eips_cache{$cache_key} = { getEIPs( \%ec2, 1 ) };
      }
      my %eips = %{ $eips_cache{$cache_key} };

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

      # Is it an EIP?
      if( defined $eips{$instance_id} ) {
         # Unlike EC2 instances, VPC instances can have multiple
         # EIPS associated with them. Use the first one from the list
         $public_ip = $eips{$instance_id}->[0];

      # Not an EIP do a DNS lookup on hostname
      } else {
         unless( defined $instance_cache{$cache_key} ) {
            $instance_cache{$cache_key} = doRequest( describeInstances( \%ec2 ), 1 );
         }
         my $instance_xml = $instance_cache{$cache_key};
         $instance_xml =~ s/\s+/ /g;
         
         if( $instance_xml =~ /<DescribeInstancesResponse/ && $instance_xml =~ /<instancesSet>(.*)<\/instancesSet>/i ) {
            my $instance_set = $1;
            foreach my $instance_data ( split /<\/item>/i, $instance_set ) {
               my( $current_id, $current_dns );
               $current_id = $1 if( $instance_data =~ /<instanceId>(.*?)<\/instanceId>/i );
               $current_dns = $1 if( $instance_data =~ /<dnsName>(.*?)<\/dnsName>/i );
               next unless( $current_id && $current_dns );

               if( $current_id eq $instance_id ) {
                  $public_ip = HostToAddr( $current_dns, 4 );
                  if( $public_ip !~ /\d+\.\d+\.\d+\.\d+/ ) {
                     $public_ip = 'INVALID_DNS';
                  } else {
                     last;
                  }
               }
            }
         } 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 ) ); 
  $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 ) );
   $response =~ s/\s+/ /g;

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

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

   return $vpcid;
}


sub parse_createnode_args($)
{
   my( $userargs ) = @_;
   my $result = [];
   foreach my $arg ( @$userargs ) {
      if( $arg =~ /^--imageid=(.+)/ ) {
         push @$result, "ImageId=$1";
      } elsif( $arg =~ /^--sizeid=(.+)/ ) {
         push @$result, "InstanceType=$1";
      } elsif ( $arg =~ /^--name=(.+)/ ) {
         push @$result, "AdditionalInfo=$1";
      }
   }
   return $result;
}

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

sub parse_instances_sets($);

sub convert_aws_status_response($)
{
   my( $xml ) = @_;

   my $obj = parseXML( \$xml );

   return "" unless defined $obj->{DescribeInstancesResponse} &&
       ref $obj->{DescribeInstancesResponse} eq 'HASH' &&
           defined $obj->{DescribeInstancesResponse}->{reservationSet} &&
               ref $obj->{DescribeInstancesResponse}->{reservationSet} eq 'HASH' &&
                   defined $obj->{DescribeInstancesResponse}->{reservationSet}->{item} &&
                       (ref $obj->{DescribeInstancesResponse}->{reservationSet}->{item} eq 'ARRAY' ||
                        ref $obj->{DescribeInstancesResponse}->{reservationSet}->{item} eq 'HASH');

   my $i_sets = $obj->{DescribeInstancesResponse}->{reservationSet}->{item};
   return parse_instances_sets( $i_sets );
}

sub convert_aws_change_response($$);

sub convert_aws_create_response($)
{
   my( $xml ) = @_;
   return convert_aws_change_response( $xml, 'RunInstancesResponse' );
}

sub convert_aws_change_response($$)
{
   my( $xml, $topelement ) = @_;

   my $obj = parseXML( \$xml );
   return "" unless defined $obj->{$topelement} &&
       ref $obj->{$topelement} eq 'HASH' &&
           defined $obj->{$topelement}->{instancesSet};

   my $i_sets = $obj->{$topelement};
   return parse_instances_sets( $i_sets );
}

sub convert_aws_destroy_response($)
{
   my( $xml ) = @_;
   return convert_aws_change_response( $xml, 'TerminateInstancesResponse' );
}

sub parse_instances_sets($)
{
   my( $i_sets ) = @_;
   # pending | running | shutting-down | terminated | stopping | stopped
   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',
                instanceType => 'sizeid',
                privateIpAddress => 'private_ip',
                ipAddress => 'public_ip',
                launchTime => 'created',
                #instanceName => 'name' # :( ec2 does not have this
              };
   my $result = "";
   my $counter = 0;
   # the xml structure of the ec2 response is this:
   # DescribeInstancesResponse => { requestid => bla,
   # reservationSet => { item => [ { instanceSet =>
   # { item => { instanceId => uniq_id,
   #             ipAddress => public_ip,
   #             privateIpAddress => private_ip,
   #             imageId => imageid,
   #             instanceState => {code => num, name => string }
   #             launchTime => created }
   # },
   # { instanceSet => { ... } } ] } }
   # There can be several instanceSets (as in the example),
   # but there can also be several instances in one
   # set (there's only one in the example).
   # So whenever there is an element called 'item', we
   # have to be prepared for a single member or an array
   # because our primitive parser only creates arrays if
   # there actually is more than one element.

   $i_sets = [ $i_sets ] unless ref $i_sets eq 'ARRAY';
   foreach my $set ( @$i_sets ) {
      next unless ref $set eq 'HASH' && defined
          $set->{instancesSet} && ref $set->{instancesSet} eq 'HASH' &&
              defined $set->{instancesSet}->{item};
      my $items = $set->{instancesSet}->{item};
      $items = [ $items ] unless ref $items eq 'ARRAY';
      foreach my $item ( @$items ) {
         next unless ref $item eq 'HASH';
         my $node = {};
	 while( my( $k, $v ) = each %$need ) {
            if( defined $item->{$k} ) {
               $node->{$v} = $item->{$k};
            } elsif( !exists $node->{$v} ) {
               $node->{$v} = 'unknown';
            }
         }
         # 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
         if( $node->{status} && ref $node->{status} eq 'HASH' &&
             defined $node->{status}->{name} &&
             defined $statusstrings->{$node->{status}->{name}} ) {
            my $awsname = $node->{status}->{name};
            $node->{status} = $statusstrings->{$awsname};
         } else {
            $node->{status} = 'unknown';
         }
         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
         }

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



# 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 ) );

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

} elsif ( $ARGV[0] eq "describe-regions" ) {
   print doRequest( describeRegions( \%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] ) );

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

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

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

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

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

} 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} );

} 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 "describe-networkinterfaces" ) {
  print doRequest( describeNetworkInterface( \%local_aws, $ARGV[1] ) );

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

   shift @ARGV;
   # we always create one node at a time:
   my @queryargs = ( "MaxCount=1",
                     "MinCount=1", "Version=2012-10-01" );

   my $userargs = parse_createnode_args( \@ARGV );

   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 $xml = doRequest( makeRequest( \%local_aws, "Action=RunInstances", @queryargs ) );
   if( !defined $xml || 0 == length( $xml ) ) {
      print STDERR "code\t500\n";
   } else {
      print "code\t202\n";
      print convert_aws_create_response( $xml );
   }
} elsif( $ARGV[0] eq 'destroynode' ) {
   shift @ARGV;
   my @queryargs = ( "Version=2012-10-01" );
   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 ) );
   if( !defined $xml || 0 == length( $xml ) ) {
      print STDERR "code\t500\n";
   } else {
      print "code\t202\n";
      print convert_aws_destroy_response( $xml );
   }
} else {
   print STDERR "Unrecognized operation: $ARGV[0]\n";
   exit 1;
}
