#!/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 set up 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 GetVPCSubnetAndCIDR
                                     GetIPv4Associations GetInterfaceId );
use Socket;

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

sub usage();

# Report an error, with optional custom tag (default EC2_INTERFACE_ERROR)
# Some errors reported are HTML-based, so strip everything between <> delimiters
sub error( $;$ )
{
   my( $error, $tag ) = @_;
   if( !defined( $tag ) ) {
      $tag = "EC2_INTERFACE_ERROR";
   }
   if( !$error ) {
      $error = "Unknown error";
   } elsif( $error =~ m|</html>| ) {
      # Remove HTML tags and combine multiple whitespace characters
      $error =~ s/<.+?>//g;
      $error =~ s/\s+/ /g;
   }
   chomp( $tag, $error );
   $error =~ s/\n/ /g; # for the logs, errors should be single-line

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


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

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

my $debug = 0;
if( grep /^--debug$/, @ARGV ) {
   $debug = 1;
}

sub debug($)
{
   my( $msg ) = @_;
   if( !$debug ) {
      return;
   }
   if( open( my $debug_fh, ">>", "$ENV{ZEUSHOME}/zxtm/log/ec2_interfaces_debug.txt" ) ) {
      print( $debug_fh "#----------------------------------------------------#\n" );
      print( $debug_fh "#$msg#\n" );
      close( $debug_fh );
   } else {
      error( "Failed to open debug file for writing" );
   }
}

debug( "$ACTION: @RESTARGS" );

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

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

##########################################
# Actions
##########################################

################## takeover-elastic <EIP> [<MAC> <PRIVIP>] #####################
if( $ACTION eq 'takeover-elastic' ) {
   my ( $IP, $MAC, $PRIVIP ) =  @RESTARGS;
   $PRIVIP = $PRIVIP || "";
   my $iface_id = "";
   my ( $instance, $err ) = RunMetaQueryRequest( 'instance-id', $METADATA_TIMEOUT );
   if( !defined( $instance ) ) {
      error( $err );
      exit( 1 );
   }

   # If we have a defined private IP, use it
   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( "No Mac address specified" );
        exit( 1 );
      }
      $MAC = lc( $MAC );
      $iface_id = GetInterfaceId( $MAC );
      if( !$iface_id ) {
         error( "Failed to get Interface ID of $MAC" );
         exit( 1 );
      }
      my( $code, $out, $err ) = execute( [ 'ip', 'addr', 'list' ] );
      if ( $code ) {
         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( "Failed to raise $PRIVIP on the system :: $err " );
                 exit( 1 );
               }
               last;
            }
         }
      }
   }

   # Now associate EIP
   my( $exit, $stdout, $stderr ) = execute( [ $AWS_TOOL, 'associate-address', $IP, $instance, $PRIVIP, $iface_id ] );
   if( $exit ) {
      error( "Failed to associate EIP '$IP' with $instance for '$PRIVIP': $stderr" );
      exit( 1 );
   }

##################### takeover-private <PRIVIP> <MAC> ##########################
} elsif( $ACTION eq 'takeover-private' ) {
   my ( $IP, $MAC ) =  @RESTARGS;
   if( !$MAC ) {
      error( "Usage: ec2-interfaces takeover private <IP> <ENI MAC>" );
      exit( 1 );
   }
   $MAC = lc( $MAC );
   my( $NETID, $err ) = RunMetaQueryRequest( "network/interfaces/macs/$MAC/interface-id" );
   if( !defined( $NETID ) ) {
      error( $err );
      exit( 1 );
   }
   my( $exit, $stdout, $stderr ) = execute( [ $AWS_TOOL, 'assign-secondary-private-address', $NETID, $IP ] );
   if( $exit ) {
      error( "Failed to assign address $IP to ENI '$NETID': $stderr" );
      exit( 1 );
   }
   # Check to see if the IP was actually raised
   ( $exit, $stdout, $stderr ) = execute( [ 'ip', 'addr', 'list' ] );
   if ( $exit ) {
      error( "Failed to check IPs on the system :: $stderr " );
      exit( 1 ); 
   }
   if ( $stdout !~ /$IP/m ) {
      # IP was not raised, raise it now
      my @ifaces = split( /^\w+?:\s/m, $stdout );
      foreach my $if ( @ifaces ) {
         if( $if =~ /$MAC/m ) {
            my( $dev ) = $if =~ /(\w+)?:/;
            my( $subnet, $cidr ) = GetVPCSubnetAndCIDR( $MAC );
            ( $exit, $stdout, $stderr ) = execute( [ "ip", 'addr', "add", "$IP/$cidr", "dev", $dev] );
            if ( $exit && ( $stderr !~ /File exists/i ) ) {
              error( "Failed to raise $IP on the system :: $stderr " );
              exit( 1 );
            }
            last;
         }
      }
   }

###################### release-elastic <EIP> [<instance>] ######################
} elsif( $ACTION eq 'release-elastic' ) {
   my ( $IP, $INST_ID ) = @RESTARGS;
   if( !$INST_ID ) {
      my ( $instance_id, $err ) = RunMetaQueryRequest( 'instance-id', $METADATA_TIMEOUT );
      if( !defined( $instance_id ) ) {
         error( $err );
         exit( 1 );
      } else {
         $INST_ID = $instance_id;
      }
   }
   my( $exit, $stdout, $stderr ) = execute( [ $AWS_TOOL, 'disassociate-address', $IP, $INST_ID ] );
   if( $exit ) {
      error( "Failed to disassociate address $IP on $INST_ID: $stderr" );
      exit( 1 );
   }

####################### release-private <PRIVIP> <MAC> #########################
} elsif( $ACTION eq 'release-private' ) {
   my ( $IP, $MAC ) = @RESTARGS;
   if( !$MAC ) {
      error( "Usage: ec2-interfaces release-private <IP> <ENI MAC>" );
      exit( 1 );
   }
   $MAC = lc( $MAC );
   my( $NETID, $err ) = RunMetaQueryRequest( "network/interfaces/macs/$MAC/interface-id" );
   if( !defined( $NETID ) ) {
      error( $err );
      exit( 1 );
   }
   my $expected_err = "Some of the specified addresses are not assigned to interface";
   my( $exit, $stdout, $stderr ) = execute( [ $AWS_TOOL, 'unassign-secondary-private-address', $NETID, $IP ] );
   if( $exit && $stderr !~ /$expected_err/ ) {
      # There was an error other than "this address is not raised..."
      error( "Failed to unassign address $IP from ENI '$NETID': $stderr" );
      exit( 1 );
   }

   # Check to see if the IP was actually dropped
   ( $exit, $stdout, $stderr ) = execute( [ 'ip', 'addr', 'list' ] );
   if ( $exit ) {
      error( "Failed to check IPs on the system :: $stderr " );
      exit( 1 ); 
   }
   if( $stdout =~ /$IP/m ) {
      # IP was not dropped, drop it now
      my @ifaces = split( /^\w+?:\s/m, $stdout );
      foreach my $if ( @ifaces ) {
         if( $if =~ /$MAC/m ) {
            my( $dev ) = $if =~ /(\w+)?:/;
            my( $subnet, $cidr ) = GetVPCSubnetAndCIDR( $MAC );
            ( $exit, $stdout, $stderr ) = execute( [ "ip", 'addr', "del", "$IP/$cidr", "dev", $dev] );
            if( $exit && ( $stderr !~ /Cannot assign requested address/i ) ) {
              error( "Failed to drop $IP from the system :: $stderr " );
              exit( 1 );
            }
            last;
         }
      }
   }

################################### current ####################################
# ZXTM calls current to determine the EIP currently associated with this VM
} elsif( $ACTION eq 'current' ) {
   my( $exit, $stdout, $stderr ) = execute( [ $AWS_TOOL, 'current' ] );
   if( $exit ) {
      error( "Failed to call 'awstool current': $stderr" );
      exit( 1 );
   }
   print $stdout;

################################### instance ###################################
# ZXTM calls instance to get its EC2 instance ID
} elsif( $ACTION eq 'instance' ) {
   my ( $instance, $err ) = RunMetaQueryRequest('instance-id', $METADATA_TIMEOUT );
   if( !defined( $instance ) ) {
      error( $err );
      exit( 1 );
   }
   print( $instance );

##################################### vpc-id ###################################

} 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, $err ) = RunMetaQueryRequest( "network/interfaces/macs/$mac/", $METADATA_TIMEOUT ); 
   if( !defined( $prop ) ) {
      error( $err );
      exit(1);
   }

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

########################### eni-subnet-associations ############################
# ZXTM calls this to get the subnets its network interfaces are in
} elsif( $ACTION eq 'eni-subnet-associations' ) {
   # Return a list of "mac=subnet-id", one per line
   my( $mac_list, $err ) = RunMetaQueryRequest( "network/interfaces/macs/", $METADATA_TIMEOUT );
   if( !defined( $mac_list ) ) {
      error( $err );
      exit( 1 );
   }
   chomp( $mac_list );
   $mac_list =~ s|/||g;
   my $mac_string = '';
   my @macs = split( "\n", $mac_list );
   foreach my $mac ( @macs ) {
      my( $subnet_id, $error ) = RunMetaQueryRequest( "network/interfaces/macs/$mac/subnet-ipv4-cidr-block/", $METADATA_TIMEOUT );
      if( $subnet_id ) {
         $mac_string .= $mac . '=' . $subnet_id . "\n";
      }
   }
   if( $mac_string ) {
      print $mac_string;
   } else {
      error( "No subnets found" );
      exit( 1 );
   }

############################# metaquery <query> ################################
# ZXTM calls this to query the meta-data server
} elsif( $ACTION eq 'metaquery' ) {
   my ( $query ) = @RESTARGS; 
   $query = $query || "";
   my ( $result, $err ) = RunMetaQueryRequest( $query, $METADATA_TIMEOUT );
   if( !defined( $result ) ) {
      error( $err );
      exit( 1 );
   } 
   print( $result );

########################### get_eip_associations ###############################
} 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() );
   if ( !scalar( @privip_to_eip_map ) ) {
      error( "No Private IP to Elastic IP mappings found" );
      exit(1);
   }
   # 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++;
   }

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

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

################################### usage ######################################
} else {
   usage();
   exit( 1 ); 

}

exit( 0 );

##########################################
# Functions 
##########################################
sub usage() {
   print STDERR "Usage: ec2-interfaces <current|instance|vpc-id|get_eip_associations|get_publicip_from_meta|metaquery|eni-subnet-associations> [args]\n";
   print <<EOF;
       current:                 Gives the current public IP of the instance using metadata
                                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 EIPs associated (if any) with private IPs
                                starting with the primary private IP of the primary network
                                interface.
       public-hostname:         Returns the public hostname. If there are multiple hostnames
                                associated with an instance (e.g. in VPC), it will return the
                                hostname which the public IP as returned by get_publicip_from_meta
                                resolves to.
       eni-subnet-associations: Returns a list of the Elastic Network Interfaces on this instance
                                by MAC address, and the subnet they are in, identified by the
                                CIDR mask.
       get_eip_associations:    Returns a list of all private IPs of the primary network interface
                                of this VPC instance and their IPv4 EIP associations in the
                                following format
                                   "<PrivateIP> <EIP> primary"
                                   "<PrivateIP> 0 secondary"
                                   "<PrivateIP> <EIP> secondary"
                                NOTE: This function only checks using the metadata server.
                                Better to use awstool "./awstool vpc-eip-associations".

      ----IP Associations----
      takeover-private:         <privip> <mac>
                                Raises the specified private IP on the interface
                                identified by the MAC address. This will remove the
                                address from any other instance automatically.
      takeover-elastic:         <eip> [mac privip]
                                Associates the given Elastic IP on this machine, using
                                the given Private IP and interface if specified.
      release-private:          <privip> <mac>
                                Lower this private IP from the interface identified by
                                the given MAC address. Returns success if this IP was not
                                raised on this interface.
      release-elastic:          <eip> [instance]
                                Release this Elastic IP from this instance, or from the
                                instance specified.

EOF
}

# Returns Mac of Primary Network Interface
sub _get_primary_mac() 
{
   #Get MAC of primary network interface
   my ( $mac, $err ) = RunMetaQueryRequest( "mac", $METADATA_TIMEOUT );
   if( !$mac ) {
      error( $err );
      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" ) ) {
      my ( $meta_eip, $err ) = RunMetaQueryRequest( "public-ipv4" );
      if( !defined( $meta_eip ) ) {
         error( $err );
         return;
      } else {
         $eip = $meta_eip;
      }
   } 
   
   return $eip;
}

sub _get_public_hostname()
{
   my ( $host, $err ) = RunMetaQueryRequest( "public-hostname" );
   if( !$host )  {
      error( $err );
      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;
}
