#!/bin/sh
#
# Script called from the REST Daemon to authenticate users using external authenticators.
#

# 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`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "restdauth: FATAL: ZEUSHOME not found"
   exit 1
fi

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -t -x $0 ${1+"$@"}

#!perl -w #"
#line 28

BEGIN {
   # Untaint input variables
   ( $ENV{ZEUSHOME} ) = ( $ENV{ZEUSHOME} =~ /^(.*)$/ );
   $ENV{PATH} = '/bin/:/usr/bin';

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

use strict;
use warnings;

use Zeus::ZXTM::AccessControl qw( authenticateUser getUserStatuses getGroupTimeout );
use Zeus::ZXTM::StorageManager;
use Zeus::Debug;
use MIME::Base64;

if( grep( /^--?h(elp)?$/, @ARGV ) ) {
   print "Authentication script. Not for direct use.\n";
   exit( 0 );
}

my $args = do{ local $/; <STDIN> };
chomp( $args );


# Untaint. Arguments should be in the form:
#   <user>\t<password>\t<client IP>
( $args ) = ( $args =~ /^(.+\t.+\t.*)$/s ); 

if( ! defined( $args ) || $args eq '' ) {
   die( "Invalid input\n" );
}

my( $user, $pass, $ip ) = split( /\t/, $args );
$pass = decode_base64( $pass );

if( ! defined( $user ) || ! defined( $pass ) ) {
   die( "Invalid input\n" );
}

D( 3, "REST authenticate - User: '", $user, "', IP: '", $ip, "'" );

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

my( $userdetails, $error_type ) = authenticateUser(
   username => $user,
   password => $pass,
   storage => $storage,
   ip => $ip
);

if( $error_type ) {
   # If the user does not exist, we do not report the user name, in-case its 
   # the user accidentialy put the password in the wrong box!
   if( $error_type eq 'invalid' ) {
      my $users_conf = $storage->getUsersConfig();
      if( ! $users_conf->userExists( $user ) ) {
         print "FAILURE\tinvalid_no_local";
         exit;
      }
   }

   print "FAILURE\t$error_type";

} elsif( $userdetails ) {
   my %statuses = getUserStatuses();
   my $status = $userdetails->{status};

   if ( !$status ) {
       # Details returned, which means authenticated in the absence of a 'status'
       $status = ( grep { $statuses{$_} eq 'Active' } keys( %statuses ) )[0];
   }

   if( $statuses{$status} eq "Active" ) {
      my $timeout = getGroupTimeout( $storage, $userdetails->{group} );
      print "SUCCESS\t$userdetails->{authname}\t$userdetails->{group}\t$timeout";
   } else {
      print "FAILURE\tstatus_$statuses{$status}";
   }
} else {
   print "FAILURE\tno_response";
}

