#!/usr/intel/bin/perl
#
# Load an /etc/passwd file and do a regex search of the name and alias fields
# Designed for mutt external query support
#
# 04-09-1998  Brandon Long (blong@fiction.net)
#   Initial Version
#

# Turn on passwd caching?  Useful when passwds are kept over NIS or 
# the OS doesn't cache local passwd entries

$CACHE = 1;
#$PWDCACHE = $ENV{"HOME"}."/.pwdcache";
$PWDCACHE = "/tmp/".$ENV{"USER"}.".pwdcache";

# These are the defines for file-locking with flock(2)
# This should lock the cache, it doesn't yet
$LOCK_SH = 1; $LOCK_EX = 2; $LOCK_NB = 4; $LOCK_UN = 8;

if (!$ARGV[0] || $ARGV[0] eq "-h")
{
  print STDERR "Syntax Error, Usage: $0 <regex>\n";
  exit(-1);
}

if ($CACHE && !out_of_date ($PWDCACHE.".pag"))
{
  print "Using cache ... ";
  dbmopen(%entries, $PWDCACHE, 0666);
}
else
{
  print "Searching pwent ... ";
  unlink ($PWDCACHE.".pag");
  unlink ($PWDCACHE.".dir");
  dbmopen(%entries, $PWDCACHE, 0666);
  while (($name, $passwd, $uid, $gid, $quota, $comment, $gcos) = getpwent)
  {
    $count++;
    $entries{$name} = $gcos;
  }
  print "$count entries ... ";
}

$count = 0;
foreach $i (keys %entries)
{
  if ($i =~ /$ARGV[0]/i)
  {
    $count++;
    push (@results, $i);
  }
  elsif ($entries{$i} =~ /$ARGV[0]/i)
  {
    $count++;
    push (@results, $i);
  }
}

print "Found $count\n";

@results = sort @results;

foreach $i (sort @results)
{
  print "$i\t$entries{$i}\n";
}

dbmclose(%entries);
exit(0);

sub out_of_date 
{
  local ($file, $expire) = @_;

# update every 12 hours unless specified less
  $expire = 0.5 unless ($expire);
  return 1 if (! -f "$file" || (-M "$file" > $expire));
  return 0;
}
