#!/usr/bin/perl
use Time::Local;
my $u;
my $list = {};
my $user = 1;
my $longuest = 0;
my $sambadir = "/usr/local/samba";
my $host = "PUT_YOUR_HOSTNAME";
my $age;
open(PIPE,"$sambadir/bin/ldbsearch -H ldap://$host -k 1 '(maxPwdAge=*)' maxPwdAge -s base|") || die "unable to search";
while(<PIPE>)
{
  if(m/maxPwdAge: -?(\d+)/)
  {
    $age = $1 / 86400 / 10000000;
  }
}
die "Unable to find max age for password" unless defined $age;
if($ARGV[0] eq "-c")
{
  $user = 0;
}
elsif( $ARGV[0] eq "-h" )
{
  print "Usage: $0 [-c|-h]\n";
  print "  List time of set password and their corresponding expiration\n";
  print "  -c option list computer account instead of user account\n";
  exit 0;
}

open(PIPE,"$sambadir/bin/ldbsearch -H ldap://$host -k 1 '(&(pwdLastSet=*)(objectClass=user))' pwdLastSet objectClass|");
my $nbclass = 0;
while(<PIPE>)
{
	next if(!m/(.*): (.*)/);
	$e = $1;
	$n = $2;

	if( $e =~ m/dn/ )
	{
		$u = $n;
    $nbclass = 0;
	}
	else
	{
    if( $e =~ m/objectClass/ )
    {
      $nbclass++;
      next;
    }
    next if( $nbclass == 5 && $user == 1);
    next if( $nbclass == 4 && $user == 0);
    $t = $n;
    $t = $t/10000000;
    $t-= 11644473600;
    
    if (defined $u)
    {
      $longuest = length($u) if(length($u) > $longuest);
      if(!defined $list->{$t})
      {
        $list->{$t} = [$u]; 
      }
      else
      {
        push @{$list->{$t}} , $u;
      }
    }
	}
}
close(PIPE);

for my $k (sort keys(%$list))
{
	my $time = $k;

	my ($s,$m,$h,$d,$M,$y) = gmtime($time);
	$y += 1900;
	$M += 1;
	$date = sprintf("%02d/%02d/%4d %02d:%02d:%02d",$d,$M,$y,$h,$m,$s);

	($s,$m,$h,$d,$M,$y) = gmtime($time + ($age * 86400));
	$y += 1900;
	$M += 1;
	$date_fin= sprintf("%02d/%02d/%4d %02d:%02d:%02d",$d,$M,$y,$h,$m,$s);

	my $users = $list->{$k};
	for my $user (@$users)
	{
		$bl = " "x( $longuest +1 - length($user) );
		print "$user" .$bl. "\t=> $date (end $date_fin) (".("%d",($time+11644473600))."0000000)\n";
	}
}
