#! /usr/bin/perl -w
#
# @(#)$Id$
#
use strict;

use POSIX;
use Getopt::Long qw(:config no_ignore_case bundling);
use Net::LDAP;
use Net::LDAP::Util qw(ldap_error_name
                       ldap_error_text); # for error handling

my $verb=0;
my $ldapurl="ldaps://ldap.nikhef.nl/";
my $ldapbase="ou=LocalUsers,dc=farmnet,dc=nikhef,dc=nl";
my $def_uidldapfilter = '(&(authorizedService=sshd)(sshPublicKey=*))';

my $ldap = Net::LDAP->new( $ldapurl, timeout=>20 );
$ldap or die "Cannot contact remote server at $ldapurl: $!\n".
             "  LDAP status: ".$ldap->error."\n";


my $results=$ldap->search(
                base=>$ldapbase,
                scope=>"sub",
                filter=>$def_uidldapfilter
                );
$results->code and die "Search failed: ".$results->error."\n";
$results->count() or die "No matching entries found, exiting\n";

my @listentries=$results->entries;

foreach my $entry ( @listentries ) {
  my $uid = $entry->get_value("uid");
  my $homeDirectory = $entry->get_value("homeDirectory");

  # only write down the ssh keys if the homedir and user exist
  -d $homeDirectory or next;
  (my $uidNumber = (getpwnam($uid))[2]) or next;

  -d "${homeDirectory}/.ssh" or mkdir "${homeDirectory}/.ssh", 0755;
  -f "${homeDirectory}/.ssh/authorized_keys" or do {
    my $FH;
    sysopen($FH, "${homeDirectory}/.ssh/authorized_keys", O_RDWR|O_CREAT|O_EXCL,0644) or
      die "Cannot create authorized_keys file for uid $uid: $_\n";
    close($FH);
    chown $uidNumber, 0, "${homeDirectory}/.ssh/authorized_keys";
    print "Created ssh authorized keys file for $uid\n";
  };

  system("mkgroup-sshlpk -o '${homeDirectory}/.ssh/authorized_keys' --uid '$uid'");
}

