#!/usr/bin/perl -w

# updates the dpass file so that users can have an up to date password

# as this is run by the crontab, you need to let it know the path to the files used
$pth = "/etc/httpd/daccess/";

# Get the list of users to go into 'dpass'
# open dgroup to get a list of the users
open GRP, "<".$pth."dgroup";
  @group = <GRP>;
close GRP;

# last line is just a carriage return so ignore that
foreach $x (0..$#group) {
  my $a = $group[$x];
  @u = split /\s+/,$a;
  #first segment of the line is the group name so discard that
  foreach $y (1..$#u) {
    my $a = $u[$y];
    $notfound = 1;
    foreach $z (@users) {
      if ($z eq $a) {
        $notfound = 0;
        last;
      };
    };
    if ($notfound == 1) {
      push (@users, $a);
    };
  };
};
# We now have a list in @users of all of the users that we want.
# Find the current hour
{
  my $t = localtime time;
  $t =~ m/(\d+):\d+:\d+/;
  $curhour = $1 * 1;
};

foreach $u (@users) {
  # for each user, open the dp[user] file, locate the current password,
  # input the file

  open USR, "<".$pth."dp$u";
    @dausr = <USR>;
  close USR;
  foreach $ln (@dausr) {
    if ($ln =~ m/$curhour\s+(\w+)/) {
      $pw = $1;
      last;
    };
  };
  #print "$u $pw\n";
  # trapdoor the password
  $cl = "htpasswd -nbms $u $pw";
  @rt = readpipe ($cl);
  $pwl = $rt[0];
  chomp $pwl;
  #print "$u $pw $pwl\n";
  # store it in the dpass array
  push (@dpasslist, $pwl);
};

# save the dpass array as the dpass file
open(DPW, ">".$pth."dpass");
  foreach $c (@dpasslist) {
    print DPW "$c\n";
  };
close(DPW);
