#!/bin/sh
#   -*- mode:perl -*-
#
# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/conf/extra
    OLD_PWD=`pwd`
    cd `dirname $0`/../../..
    if [ -d 'zxtm/bin' ]
    then
       ZEUSHOME=`pwd`
       export ZEUSHOME
       cd $OLD_PWD
    fi
fi

if [ -z "$ZEUSHOME" ]
then
   echo Please set the ZEUSHOME environment variable 1>&2
   exit 1
else
   PROG=$ZEUSHOME/perl/miniperl
fi

exec $PROG -x $0 ${1+"$@"}
#!perl -w
#line 29

BEGIN {
   if( defined $ENV{ZEUSHOME} ) {
      unshift( @INC, "$ENV{ZEUSHOME}/zxtmadmin/lib/perl",
               "$ENV{ZEUSHOME}/admin/lib/perl",
               "$ENV{ZEUSHOME}/zxtm/lib/perl",
               "$ENV{ZEUSHOME}/perl" );
   }
}

use strict;
use warnings;
use Zeus::ZXTM::ZJSON qw( formatJSON );
use Zeus::Execute qw( execute );

# print usage information:
sub usage(;$);

# convert cmd-line arguments to args used by our functions
# args: ( \@ARGV, $args )
# returns: 0 on success, 1 on failure
sub process_arguments($$);

# Parse credentials to extract names into @names list
# returns: 0 on success, 1 on failure
sub get_names($);

my $dnslookup = "$ENV{ZEUSHOME}/zxtm/bin/dnslookup";
my $args = { action => undef, arguments => {}, result => "unknown", status => 137 };
my ( $ns_server, $ns_port ) = undef;

if( process_arguments( \@ARGV, $args ) ) {
   print STDERR "Usage: $0 status --poolname=name\n";
   exit 1;
}

my @names;
if( 0 != get_names( $args->{arguments} ) ) {
   print STDERR "Couldn't get any names from poolfile\n";
   exit -1;
}

# For our automated testing, use port 5353, rather than rewrite /etc/resolv.conf
if ( defined( $ns_server ) && defined ( $ns_port ) ) {
   $dnslookup .= " -s $ns_server -p $ns_port";
}

my $code = 200;   # Default return code
my @ip_addrs;
my @no_results;
foreach my $name ( @names ) {
   # Find all IPv4 and IPv6 addresses
   my( $exit, $stdout, $stderr ) = execute( "$dnslookup -a $name" );
   if( $exit ) {
     if ( $stderr =~ m/Timed out/ ) {
        $code = 500;
     } elsif ( $stderr =~ m/No server listening/ ) {
        $code = 500;
     } elsif ( $stderr =~ m/Lookup Failed/ ) {
        push( @no_results, $name );
     } else {
        die( "Failed to run $dnslookup: $stderr\n");
     }
   }
   chomp $stdout;
   my (undef, @found_ips) = split( /\t/, $stdout );
   push( @ip_addrs, @found_ips );
}


# Use cloud credentials name to identify nodes as part of the pool
my $imageid = $args->{arguments}->{poolname};
my $result = { NodeStatusResponse => { code => $code, version => 1 } };
my $nodes = [];
my $now = time();

# Create formatted response
foreach my $ip ( @ip_addrs ) {
   my $node_details = {};
 
   $node_details->{'sizeid'} = '';
   $node_details->{'status'} = 'active';
   $node_details->{'public_ip'} = $ip;
   $node_details->{'private_ip'} = $ip; 
   $node_details->{'complete'} = 100;

   $node_details->{'uniq_id'} = $ip;
   $node_details->{'imageid'} = $imageid;
   $node_details->{'created'} = $now;
   push( @$nodes, $node_details );
}

# Create formatted response
foreach my $nothing_found ( @no_results ) {
   my $node_details = {};

   $node_details->{'sizeid'} = '';
   $node_details->{'status'} = 'notfound';
   $node_details->{'hostname'} = $nothing_found;
   $node_details->{'public_ip'} = "0.0.0.0";
   $node_details->{'private_ip'} = "0.0.0.0"; 
   $node_details->{'complete'} = 100;

   $node_details->{'uniq_id'} = "0.0.0.0";
   $node_details->{'imageid'} = $imageid;
   $node_details->{'created'} = $now;
   push( @$nodes, $node_details );
}

$result->{NodeStatusResponse}->{nodes} = $nodes;

print STDOUT formatJSON( $result );

exit 0;

# internal methods follow
sub process_arguments($$)
{
   my( $argv, $args ) = @_;

   my $failed = 0;

   # parse args:
   if( defined( $argv ) && ref( $argv ) eq 'ARRAY' && scalar( @$argv ) > 0 ) {
      $args->{action} = shift @$argv;
      foreach my $arg( @$argv ) {
         $args->{arguments}->{$1} = $2 if( $arg =~ /--([^=]+)=(.+)/ );
      }

      if( $args->{action} eq '--help' ) {
         usage();
         exit( 0 );
      } elsif( $args->{action} ne 'status' ) {
         print STDERR "Unkown action: '$args->{action}'\n\n";
         $failed = 1;
      }
   }
   if( !defined( $args->{action} ) ) {
      print STDERR "No action given\n\n";
      $failed = 1;
   }

   return $failed;
}

sub get_names( $ )
{
   my( $arguments ) = @_;

   my $poolname = $arguments->{poolname};
   my $nameserver = $arguments->{nameserver};

   my $zhome = $ENV{ZEUSHOME};
   if( !defined $poolname ) {
      print STDERR "No poolname provided\n";
      return 1;
   }
   if( defined $nameserver ) {
      ($ns_server, $ns_port ) = split( /:/, $nameserver );
   }

   my $file = "$zhome/zxtm/conf/pools/$poolname";
   if( ! -r $file ) {
      print STDERR "Pool file '$file' not readable\n";
      return 1;
   }

   my $config = {};

   if( open( POOL, $file ) ) {
      while( <POOL> ) {
         $config->{$1} = $2 if /^\s*(\S+)\s+(.*)/;
      }
      close( POOL );

      if( exists $config->{'dns_autoscale!hostnames'} ) {
         @names = split( / +/, $config->{'dns_autoscale!hostnames'} );
         return 0;
      } else {
         return 1; # means failure
      }
   } else {
      print STDERR "failed to open file $file\n";
      return 1;
   }
}

sub usage(;$)
{
   my( $error ) = @_;

   print <<EOF;
Usage: dns_autoscaling status --poolname=<poolname>

This script is used to resolve DNS entries for a pool's nodes

REQUIRED Arguments:

status                    Queries the DNS for the IPv4 and IPv6 addresses of the
                          hostnames specified by the "dns_autoscaling!hostnames"
                          key, and returns a JSON status.

--poolname=poolname       The pool file to be queried.
--nameserver=addr:port    The nameserver to be queried. Defaults to those listed
                          in /etc/resolv.conf

EOF

   die( $error ) if( $error );
}
