#!/bin/sh

# EC2 Interfaces Script
#
# Talks to the Amazon metadata API, see
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.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

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

use strict;
use Zeus::Execute qw( execute );
use Zeus::ZXTM::EC2::EC2Metadata qw( RunMetaQueryRequest GetAllPrivateIPsFromMetadata
                                     GetIPv4Associations GetInterfaceId GetVPCSubnetAndCIDR
                                     GetAllMacsFromMetadata );
use Socket;

sub _get_primary_mac(); 
sub _get_publicip_from_meta();
sub _get_public_hostname();

sub usage();

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

   # Report the error                                                                                                                                  
   print STDERR "$tag\t$error\n";
}


if( grep /^--?h(elp)?$/, @ARGV ) {
   usage();
   exit( 0 );
}

my( $ACTION, @RESTARGS ) = @ARGV;
$ACTION ||= '';

my $ZEUSHOME = $ENV{ZEUSHOME};
my $METADATA_TIMEOUT = 5;   # metadata server should respond faster than AWS as its inside EC2
my $PLATFORM = `uname`;

my $AWS_TOOL = "$ZEUSHOME/zxtm/bin/awstool";

# ZXTM calls interface takeover <EIP> <PRIVIP> to 'raise' an EIP TIP
if( $ACTION eq 'takeover' ) {

   my ( $IP, $PRIVIP, $MAC ) =  @RESTARGS;
   $PRIVIP = $PRIVIP || "";
   my ( $instance ) = RunMetaQueryRequest( 'instance-id', $METADATA_TIMEOUT );
   if( !defined( $instance ) ) {
      exit( 1 );
   }

   my $iface_id = "";
   if ( $PRIVIP && $PRIVIP ne "0.0.0.0" ) {
      # Raise the secondary IP not already raised
      # Get mac to find out about which device to use
      $MAC ||= _get_primary_mac();
      if ( !$MAC ) {
        error( "EC2_INTERFACE_ERROR", "No Mac address specified" );
        exit (1);
      }
      $MAC = lc( $MAC );
      $iface_id = GetInterfaceId( $MAC );
      if( !$iface_id ) {
         error( "EC2_INTERFACE_ERROR", "Failed to get Interface ID of $MAC" );
         exit (1);
      }
      my( $code, $out, $err ) = execute( [ 'ip', 'addr', 'list' ] );
      if ( $code ) {
         error("EC2_INTERFACE_ERROR", "Failed to check IPs on the system :: $err ");
         exit( 1 ); 
      }

      if ( $out !~ /$PRIVIP/m ) {
         my @ifaces = split(/^\w+?:\s/m, $out);
         foreach my $if ( @ifaces ) {
            if ( $if =~ /$MAC/m ) {
               my ( $dev ) = $if =~ /(\w+)?:/;
               my ( $subnet, $cidr ) = GetVPCSubnetAndCIDR( $MAC );
               my( $code, $out, $err ) = execute( [ "ip", 'addr', "add", "$PRIVIP/$cidr", "dev", $dev] );
               if ( $code && ( $err !~ /File exists/i ) ) {
                 error("EC2_INTERFACE_ERROR", "Failed to raise $PRIVIP on the system :: $err ");
                 exit( 1 );
               }
               last;          
            }
         } 
      }
   } # No Priv IP
 
   # Now associate EIP      
   if( system( "$AWS_TOOL associate-address $IP $instance $PRIVIP $iface_id > /dev/null" ) == 0 ) {
      exit( 0 );
   } else {
      exit( 1 );
   }
   
# ZXTM calls release <EIP> to 'lower' an EIP TIP (only when the
# TIP is being disabled - not necessary when doing failover)
} elsif( $ACTION eq 'release' ) {
   my ($IP, $INSTANCEID ) = @RESTARGS;
   if( !$INSTANCEID ) {
      ( $INSTANCEID ) = RunMetaQueryRequest( 'instance-id', $METADATA_TIMEOUT );
      if( !defined( $INSTANCEID ) ) {
         exit( 1 );
      }
   }
   if( system( "$AWS_TOOL disassociate-address $IP $INSTANCEID > /dev/null" ) == 0 ) {
      exit( 0 );
   } else {
      exit( 1 );
   } 

# ZXTM calls current to determine the EIP currently associated with this VM
} elsif( $ACTION eq 'current' ) {

   my $result = `$AWS_TOOL current`;
   exit( 1 ) if( $? != 0 );
   print $result;
      
# ZXTM calls instance to get its EC2 instance ID
} elsif( $ACTION eq 'instance' ) {

   my ( $instance ) = RunMetaQueryRequest('instance-id', $METADATA_TIMEOUT );
   if( !defined( $instance ) ) {
      exit( 1 );
   }
   print( $instance );
      
# ZXTM calls this to query the meta-data server 
} elsif( $ACTION eq 'vpc-id' ) {
   my $mac = _get_primary_mac();

   if ( !$mac ) {
      exit(1);
   } 

   # First check the properties so that we can
   # distinguish between EC2 and VPC instance
   my ( $prop ) = RunMetaQueryRequest( "network/interfaces/macs/$mac/", $METADATA_TIMEOUT ); 
   if( !defined( $prop ) ) {
      exit(1);
   }

   #Check VPC id is one of the them
   if ( $prop =~ m/vpc-id/ ) {
      my ( $vpcid ) = RunMetaQueryRequest( "network/interfaces/macs/$mac/vpc-id/", $METADATA_TIMEOUT );
      if( !defined( $vpcid  ) ) {
         exit(1);
      }
      print( $vpcid );
   }

} elsif( $ACTION eq 'metaquery' ) {
   my ( $query ) = @RESTARGS; 
   $query = $query || "";
   my ( $result ) = RunMetaQueryRequest( $query, $METADATA_TIMEOUT );
   if( !defined( $result ) ) {
      exit( 1 );
   } 
   print( $result );

} elsif( $ACTION eq 'get_eip_associations' ) {
  #TODO: We should get rid of this
  # GetEIP asscoiation using metadata server only
  # NOTE: This function only checks using meta data server. Better to use
  #       awstool "./awstool vpc-eip-associations"
  my @privip_to_eip_map = GetIPv4Associations( _get_primary_mac() );
  exit(1) if ( !( @privip_to_eip_map ) );
  # Print 
  my $i = 0;
  foreach my $ip ( @privip_to_eip_map ) {
     my $pip = $ip->[0];
     my $eip = $ip->[1] || "0";
     my $type = ($i)?'secondary':'primary';
     print "$pip $eip $type\n";
     $i++;
  } 

} elsif( $ACTION eq 'get_publicip_from_meta' ) {
  # It gets EIP using metadata only 
  # "current" should be used form ZXTM
  my $ip = _get_publicip_from_meta();
  if ( $ip ) {
     print $ip;
  } else {
     exit(1);
  }

} elsif( $ACTION eq 'public-hostname' ) {
  #Get the public hostname
  # If instance has multiple, it will return
  # what's associated with primary private IP
  # of primary ENI
  my $host = _get_public_hostname();
  if ( $host ) {
     print $host;
  } else {
     exit(1);
  }
} else {
   usage();
   exit( 1 ); 
}

exit( 0 );

##########################################
# Functions 
##########################################
sub usage() {
   print STDERR "Usage: ec2-interfaces <takeover|release|current|instance|vpc-id|get_eip_associations|get_publicip_from_meta|metaquery|all_private_ips> [args]\n";
   print <<EOF;
       current:                 Gives current public IP of the instance using metadata but 
                                but also checks the describe-addresses call to verify 
                                that the current IP isn't an EIP assigned to another machine.
       get_publicip_from_meta:  Gives public IP only using metadata. 
                                For VPC instances, current and get_publicip_from_meta 
                                will return EIP associated (if any ) with private IP 
                                starting with primary private IP of primary network interface. 
       public-hostname:         Returns public hostname. If there are multiple hostnames associated 
                                with an instance e.g. in VPC, it will return hostname
                                which public IP as returned by get_publicip_from_meta resolves to.
       get_eip_associations:     Returns list of all private IPs of Primary network intrface of 
                                this VPC instance and their IPv4 EIP associations in following 
                                format
                                   "<PrivateIP> <EIP> primary"
                                   "<PrivateIP> 0 secondary" 
                                   "<PrivateIP> <EIP secondary" 
                                 NOTE: This function only checks using meta data server. 
                                 Better to use awstool "./awstool vpc-eip-associations"
              
EOF
}

# Returns Mac of Primary Network Interface
sub _get_primary_mac() 
{
   #Get MAC of primary network interface
   my ( $mac ) = RunMetaQueryRequest( "mac", $METADATA_TIMEOUT );
   if( !$mac ) {
      return;
   }
 
   chomp( $mac );
   $mac = lc($mac);
   return $mac;
}

# Get The Public IP of an instance just using metadata
# It returns IP which is
# Returns
#     - EIP IP associated with primary private IP of primary network interface
#     - EIP associated with Secondary private ip starting from first one of 
#        primary network interface
#     - Failing that, whatever meta-data/public-ipv4 returns.
# KEEP THIS IN SYNC WITH WHAT IS SAID IN Usage()
#     
sub _get_publicip_from_meta()
{
   my @priv_ip_to_eip_map = GetIPv4Associations( _get_primary_mac() );
   my $eip = undef;

   if( @priv_ip_to_eip_map ) {
      for( my $index = 0; $index < @priv_ip_to_eip_map; $index++ ) {
         my $pip = $priv_ip_to_eip_map[$index]->[0];
         $eip = $priv_ip_to_eip_map[$index]->[1];
         last if ( $eip && $eip ne "0.0.0.0" );
      }

   }
   
   if( !$eip || ( $eip eq "0.0.0.0" ) ) {
      ( $eip ) = RunMetaQueryRequest( "public-ipv4" );
      if( !defined( $eip ) ) {
         return;
      }
   } 
   
   return $eip;
}

sub _get_public_hostname()
{
  my ( $host ) = RunMetaQueryRequest( "public-hostname" );
  if( !$host )  {
     return;
  }

  # Get public IP so that we can return its hostname
  my $publicip = _get_publicip_from_meta();

  my @all_hosts = split(/amazonaws\.com/, $host );
  if( ( scalar( @all_hosts ) > 1 ) && $publicip ) {
     # Set host to empty string as we either want to return something
     # useful or nothing
     $host = "";
 
     my $name = gethostbyaddr( inet_aton($publicip), AF_INET );
     if( $name ) {
        foreach my $h ( @all_hosts ) {
	        $h = $h . 'amazonaws.com';
           if( $name eq $h ) {
              return $h;
           }
         }
     }
   }

  return $host;

}
