#!/usr/bin/perl
# Update IPDB users table with user/password data from 5-minute
# cron'ed push from billing
###
# SVN revision info
# $Date: 2007-12-11 20:27:18 +0000 (Tue, 11 Dec 2007) $
# SVN revision $Rev: 374 $
# Last update by $Author: kdeugau $
###
# Copyright (C) 2007 - Kris Deugau

use strict;
use warnings;
use DBI;
use MyIPDB;

my $ip_dbh;
my $errstr;
($ip_dbh,$errstr) = connectDB_My;
if (!$ip_dbh) {
  die "Database error: $errstr\n";
}
initIPDBGlobals($ip_dbh);

my %userhash;

open HTPASS, "</var/www/ipdb.example.com/ip/.htpasswd";

my $sth = $ip_dbh->prepare("select count(*) from users where username=?");

while (<HTPASS>) {
  chomp;
  my ($user,$pass) = split /:/;
  $sth->execute($user);
  my @data = $sth->fetchrow_array();
  my $sql;
  if ($data[0] == 0) {
    $sql = "insert into users (username,password) values ('$user','$pass')";
  } else {
    $sql = "update users set password='$pass' where username='$user'";
  }
  my $sth2 = $ip_dbh->prepare($sql);
  $sth2->execute or print "error executing $sql: ".$DBI::errstr."\n";
  $userhash{$user} = $pass;
}
my @userlist = @{ $ip_dbh->selectall_arrayref("select username from users") };
$sth = $ip_dbh->prepare("delete from users where username=?");
foreach my $user (@userlist) {
  $sth->execute if !$userhash{$user}
    or print "error deleting $user: ".$DBI::errstr."\n";
}
