#!/usr/bin/perl -w


# argo-voms-htpasswd
# Steve Traylen <steve.traylen@cern.ch> September 29th
# Uses configuration file /etc/argo-voms-htpasswd/argo-voms-htpasswd.conf
# Run as 
# argo-voms-htpasswd -o /etc/nagios/htpasswd.users
# Will generate a argo-voms-htpasswd

use strict;
use SOAP::Lite;
use URI;
use Getopt::Std;
use LWP::UserAgent;
use XML::DOM;
use JSON;

use vars qw/ %opt /;

sub usage() {
  print STDERR << "EOF";

  Generates a htpasswd file suitable for a use with Apache's
  FakeBasicAuth Configuration.

  usage: $0 -o <filename> || -h [-c <configfile> ] [-s <directory>]
     -o <filename>   : Specify file name to write htpasswd file to.
                       This output file must be specifed.
     -h              : Print this help
     -c <configfile> : Configuration file of voms URLs.
                       Default /etc/argo-voms-htpasswd/argo-voms-htpasswd.conf
     -s <directory>  : Directory containing files (*.conf) with static lists of
                       DNs to add to the generated configuration file.
                       Default: /etc/argo-voms-htpasswd/argo-voms-htpasswd.d
                       Such a file in this directory should contain DNs , one per line.
                       # This is a comment
                       /DC=ch/DC=example/CN=Fred Astaire
                       /DC=ch/DC=example/CN=Ginger Rogers

     -b <banfile>    : File containing DNs that will be excluded from the 
                       configuration. 
                       Such a file in this directory should contain DNs , one per line.
                       # This is a comment
                       /DC=ch/DC=example/CN=Fred Astaire
                       /DC=ch/DC=example/CN=Ginger Rogers

     -e <Email|emailAddress> : 
                       Use "Email" or "emailAddress" as field
                       name for subject DNs that contain an
                       email address specification.
                       Default: emailAddress.

  Configuration File Format Example:

vomss://voms.cern.ch:8443/voms/ops?/ops/
vomss://glite-io.scai.fraunhofer.de:8443/voms/dech?/dech
vomss://voms.cern.ch:8443/voms/atlas?/atlas/usatlas/Role=production
gocdb://goc.gridops.org/gocdbpi/private/?method=get_site_contacts&sitename=SITE
gocdb://goc.gridops.org/gocdbpi/private/?method=get_site_contacts&roc=ROCNAME
gocdb://goc.gridops.org/gocdbpi/private/?method=get_roc_contacts&roc=ROCNAME

EOF
  exit ;
}


my $config = '/etc/argo-voms-htpasswd/argo-voms-htpasswd.conf' ;
my $email_field = '/emailAddress=' ;
my $staticd     = '/etc/argo-voms-htpasswd/argo-voms-htpasswd.d' ;
my $bans_config = '/etc/argo-voms-htpasswd/argo-voms-htpasswd-bans.conf';
# count users found from external sources
my $counter = 0;
# count external sources
my $source_counter = 0;

getopts("ho:c:e:s:b:", \%opt ) or usage() ;
$config = $opt{c} if $opt{'c'} ;
$staticd = $opt{s} if $opt{'s'} ;
$email_field = '/'.$opt{'e'}.'=' if $opt{'e'} ;
$bans_config = $opt{b} if $opt{'b'} ;
usage() if $opt{h} ;
usage() unless $opt{o} ;


# Hardcode these.
$ENV{HTTPS_CA_DIR}    = "/etc/grid-security/certificates" ;
$ENV{HTTPS_CERT_FILE} = "/etc/grid-security/hostcert.pem" ;
$ENV{HTTPS_KEY_FILE}  = "/etc/grid-security/hostkey.pem" ;
my $VOMS_NS  = 'http://glite.org/wsdl/services/org.glite.security.voms';
my $VOMS_ATTRIBUTE_NS = 'http://glite.org/wsdl/services/org.glite.security.voms.service.attributes';

my %bans;
open(BANS,"$bans_config") or die "Could not open $bans_config: $!\n" ;
while (<BANS>)
{
   chomp;
   $bans{ $_ } = 1;
}
close(BANS) or die "Could not close $bans_config: $!\n" ;

open(CONFIG,"$config") or die "Could not open $config: $!\n" ;
my $output = "" ;

# Work through each line of the configuration.
while (<CONFIG> ) {
     chomp;
     my $configline = $_ ;
     if ( m/^#/ ||  m/^\s*$/ ) {
        next ;
     }
     elsif ( s/^vomss:/https:/ ) {
        $source_counter++;

        # Remove a trailing slash.
        $_ =~ s/\/$// ;

        my $vomsuri = URI->new($_);
        unless ($vomsuri) {
            print STDERR "$_ not a valid URI: $!\n" ;
            # next;
            exit 1;
        }
        my $proxy = 'https://'.$vomsuri->host_port().$vomsuri->path().'/services/VOMSAdmin' ;
        my $query = $vomsuri->query() ;

        my $admin =  new SOAP::Lite
                 uri => 'urn:VOMS',
                 proxy => $proxy, 
                 on_fault => sub {
                      my($soap, $res) = @_;
                      unless (ref $res) {
                           print STDERR "Failed on $configline: ".$soap->transport->status . ": Try $proxy?method=listMembers" ."\n";
                           return;
                      }
                      if (defined $res->faultdetail()->{exceptionName}) {
                           print STDERR "Failed on $configline: ".$res->faultdetail()->{exceptionName} . ": " .
                                    $res->faultstring() . ": Try $proxy?method=listMembers"."\n";
                           return;
                      }
                      else {
                           print STDERR "Failed on $configline: ".$res->faultstring() . ": Try $proxy?method=listMembers" ."\n";
                           return;
                      }
                 };
        $admin->transport->http_request->header('X-VOMS-CSRF-GUARD' => '');
        $admin->transport->ssl_opts(SSL_key_file => $ENV{HTTPS_KEY_FILE}, SSL_cert_file => $ENV{HTTPS_CERT_FILE});
        $admin->serializer()->maptype->{'User'} = $VOMS_NS;
        $admin->serializer()->maptype->{'ACLEntry'} = $VOMS_NS;
        $admin->serializer()->maptype->{'QalifiedRole'} = $VOMS_NS;
        $admin->serializer()->maptype->{'Attribute'} = $VOMS_ATTRIBUTE_NS;

        $output = $output."### Members of $vomsuri\n" ;
        my $users = $admin->listMembers($query);
        unless ($users) {
            print STDERR "Could not list members: $! of URL: $_\n" ;
            # next;
            exit 1;
        }
        $users = $users->result();
        unless ($users) {
            print STDERR "Could not get result of method listMembers: $! of URL: $_\n" ;
            # next;
            exit 1;
        }

        foreach my $user (@$users) {
                my $mail = "Not Entered" ;
                $mail = $$user{'mail'} if $$user{'mail'} ;
                my $CN = "Not Entered" ;
                $CN = $$user{'CN'} if $$user{'CN'} ;
                my $DN = $$user{'DN'} ;
                $DN =~ s{/[Ee]mail(Address)?=}{$email_field} ;
                if (!exists $bans{$DN}) {
                    $output =  $output."## CN = ".$CN.", Email = ".$mail."\n" ;
                    $output =  $output.$DN.':xxj31ZMTZzkVA'."\n"  ;
                    $counter++ ;
                }
        }
    } elsif ( s/^gocdb:/https:/ ) {
        $source_counter++;

        my $ua = LWP::UserAgent->new(env_proxy=>1, ssl_opts => { SSL_key_file => $ENV{HTTPS_KEY_FILE}, SSL_cert_file => $ENV{HTTPS_CERT_FILE} });
        $ua->agent("argo-voms-htpasswd");
        my $req = HTTP::Request->new(GET => $_);
        my ($roletype) = $_ =~ m/&roletype=(.*)&/;
        if (!$roletype) {
           ($roletype) = $_ =~ m/&roletype=(.*)$/;
        };
        my $res = $ua->request($req);
        if (!$res->is_success) {
            print STDERR "Could not get results from GOCDB: ".$res->status_line . "\n Of URL: $_ \n";
            # next;
            exit 1;
        }

        my $parser = new XML::DOM::Parser(ErrorContext => 2);
        my $doc;
        eval {
            $doc = $parser->parse($res->content);
        };
        if ($@) {
            print STDERR "Error parsing GOCDB XML response: ".$@. "\n Of URL: $_ \n";
            # next;
            exit 1;
        }

        $output = $output."### Members of $_\n" ;
        my $members;

        foreach my $site ($doc->getElementsByTagName("CONTACT")) {
            if ((!$roletype) or ($site->getElementsByTagName("ROLE_NAME") && $site->getElementsByTagName("ROLE_NAME")->item(0)->getFirstChild->getNodeValue() && $site->getElementsByTagName("ROLE_NAME")->item(0)->getFirstChild->getNodeValue() eq $roletype)) {
                foreach my $elem ($site->getElementsByTagName("CERTDN")) {
                    my $value = $elem->getFirstChild->getNodeValue() if ($elem->getFirstChild);
                    if ($value) {
                        $members->{$value} = 1;
                        last;
                    }
                }
            }
        }
        foreach my $contact (keys %$members) {
            if (!exists $bans{$contact}) {
                $output =  $output.$contact.':xxj31ZMTZzkVA'."\n";
                $counter++ ;
            }
        }

        $doc->dispose;
    } else {
        # report invalid line, but don't exit
        print STDERR "Invalid config line $_\n" ;
        # exit 1 ;
    }

}
close(CONFIG) or print STDERR "Could not close $config: $!\n" ;

# SAM-1864
# if
#   (1) external sources (GOCDB, VOMS) are defined and
#   (2) didn't return any users and
#   (3) htpasswd file exists
# assume that communication with external sources is failing
# and keep the existing htpasswd file
if ($source_counter > 0 && $counter == 0 && -f $opt{o}) {
    print STDERR "Found 0 users from external sources. Keeping the existing config file.\n" ;
    exit 1;
}


# Now work through the files in static.d
opendir(STATIC,$staticd)  ;
foreach my $f ( readdir (STATIC)) {
   next unless ($f  =~ m/.conf$/ ) ;
     $output = $output."\n# Loading static DNs from $staticd/$f\n" ;
     open (F,$staticd.'/'.$f) or die "Could not open $staticd".'/'."$f: $!\n" ;
     while(<F>){
       chomp;
       if ( /^[^#\s]/ ) {
         $output = $output.$_.':xxj31ZMTZzkVA'."\n"  ;
       }
     }
     close(F) ;
}



open(OUTPUT,">$opt{o}") or die "Could not open $opt{o}: $!\n"  ;
print OUTPUT  $output ;
close (OUTPUT) or die "Could not close $opt{o}: $!\n" ;



