#!/usr/bin/perl -w

# perl script to add users to Document Manager's users table in RDBMS

use Digest::MD5 qw(md5_hex);
use DBI;

# php dbi to Perl dbi translation of database drivers (DBDs)
my %dbi_trans = (
	"pgsql" => "Pg",
	"mysql" => "mysql",
	"odbc" => "ODBC",
	"oracle" => "Oracle"
	);

my $login = shift @ARGV;

if (defined $login && $login eq "-h") {
	print "Usage: $0 [login] [full name] [password] [email]\n";
	exit;
}

while (! $login) {
	print "login: ";
	$login=<STDIN>; chomp $login;
}

my $fullname = shift @ARGV;
while (! $fullname) {
	print "full name: ";
	$fullname=<STDIN>; chomp $fullname;
}

my $passwd = shift @ARGV;
if (! $passwd) {
	print "password [auth_pop3]: ";
	$passwd=<STDIN>; chomp $passwd;
	if ($passwd eq "") {
		$passwd="auth_pop3";
	}
}
if (substr($passwd,0,5) ne "auth_") {
		$passwd=md5_hex($login.$passwd);
}

my $email = shift @ARGV;
while (! $email || $email !~ /\w@\w/) {
	print "e-mail: ";
	$email=<STDIN>; chomp $email;
	print "e-mail address needs to have user\@domain for auth_pop3",
	      " to work!\n" if ($email !~ /\w@\w/);
}

my $conffile=".docman.conf";

while (! -e $conffile) {
	print "docman conf file [docman.conf]: ";
	$conffile=<STDIN>; chomp $conffile;
	if ($conffile eq "") {
		$conffile="docman.conf";
	}
}

my $dbi_sql;	# this will be filled from docman's config file
my $dbi;	# this will be filled with connect string

open(CONF,$conffile) || die "open $conffile: $!";
while(<CONF>) {
	chomp;
	if (/(\$dbi[^;]+;)/i) {
		eval $1;
	}
}
close(CONF);

if (! defined $dbi) {
	print STDERR "ERROR: can't find DBI connect docman conf file, aborting!\n";
	exit 1;
} else {
	($php_dbd,$db,$db_login,$db_passwd) = split(/:/,$dbi);
}

if (! defined $dbi_sql) {
	print STDERR "ERROR: can't find SQL query in docman conf file, aborting!\n";
	exit 1;
} else {
	if ($dbi_sql =~ m/select\s+(.+)\s+from\s+(.+)/i) {
		($cols,$table) = ($1,$2);
	} else {
		print STDERR "ERROR: can't parse SQL query '$dbi_sql', aborting!\n";
		exit 1;
	}
}

my $dbh = DBI->connect("DBI:".$dbi_trans{$php_dbd}.":dbname=$db","$db_login","$db_passwd") || die $DBI::errstr;
my $sql = "insert into $table ($cols) values ('$login','$fullname','$passwd','$email')";
$dbh->do("$sql") || die $dbh->errstr();
$dbh->disconnect;

