#!/usr/bin/perl


$YPCAT = '/usr/bin/ypcat';
$NIUTIL = '/usr/bin/niutil';
$LISTUSERS = "$NIUTIL -list . /users";
$DELETEUSER = "$NIUTIL -destroy / /users/%s";
$NILOAD = '/usr/bin/niload passwd .';
$FINDMORTALS = '/usr/bin/nigrep mortality . /users';
@PropList = qw( passwd uid gid realname home shell );

$/ = "\n";
open(PASSWD_MAP,"$YPCAT passwd|") || die "Cannot ypcat passwd\n";
$passwdHash = &readPasswd(PASSWD_MAP);
close(PASSWD_MAP);

open(SHADOW_MAP,"$YPCAT passwd.adjunct.byname|") || 
     die "Cannot ypcat passwd.adjunct.byname\n";
$shadowHash = &readShadow(SHADOW_MAP);
close(SHADOW_MAP);

$doit = 0;
foreach $_ (keys %$passwdHash) {
      print "$_\n";
      system "echo '$_:$shadowHash->{$_}:$passwdHash->{$_}' | $NILOAD";
      system "$NIUTIL -createprop / /users/$_ mortality 1";
      sleep 2;
}

exit;

# Now I have all entries in NI database. I want to delete some.

open(NIDUMP, "$FINDMORTALS|") || die "Cannot open NetInfo\n";
while ( <NIDUMP> ) {
  if ( m!/users/([^:]+):! && undefined($passwdHash->{$1}) ) {
     system sprintf($DELETEUSER, $1);
     print "user cancellato: $1"; 
  }
}
close(NIDUMP);

sub frob10fields () {
  local $" = ':';
  my @list = split(':', shift, 5);
  ## WARNING ## I am losing the password field in this way
  return ($list[0], "@list[2..3]::0:0:$list[4]");
}

sub readPasswd () {
  my $fh = shift;
  my $res = {};
  my @tmp;
  while ( <$fh> ) {
    chomp;
    @tmp = &frob10fields($_); 
    $res->{$tmp[0]} = $tmp[1];
  }
  return $res;
}

sub readShadow () {
  my $fh = shift;
  my $res = {};
  my $encrypted_password;
  my $dum;
  while ( <$fh> ) {
    ($_, $encrypted_password, $dum) = split(':', $_, 3);
    $res->{$_} = $encrypted_password;
  }
  return $res;
}

sub readSysPasswd () {
  my $fh = shift;
  my $res = {};
  my $dum;
  while ( <$fh> ) {
    ($_, $dum) = split(':', $_, 2);
    $res->{$_} = 1;
  }
}

