#! /usr/bin/perl
#
#  Convert vchkpw to userdb format.
#
#  $Id: vchkpw2userdb.in,v 1.4 2000/02/16 01:12:13 mrsam Exp $
#
# Copyright 1998 - 1999 Double Precision, Inc.  See COPYING for
# distribution information.

use Getopt::Long;

die "Invalid options.\n" unless
	GetOptions("vpopmailhome=s" => \$vpopmailhome,
		"todir=s" => \$todir);

if ( ! ( $vpopmailhome =~ /./ ))
{
	(undef, undef, undef, undef, undef, undef, undef, $vpopmailhome)
			= getpwnam("vpopmail");

	die "Cannot find vpopmail home.\n" unless $vpopmailhome =~ /./;
}

-d "$vpopmailhome" || die "$vpopmailhome: not found.\n";

if ( $todir =~ /./ )
{
	-d "$todir" || mkdir($todir, 0700) || die "$!\n";
}

$bindir=$0;

if ($bindir =~ /^(.*)\/[^\/]*$/ )
{
	$bindir=$1;
}
else
{
	$bindir=".";
}

die "Unable to locate pw2userdb.\n" unless -f "$bindir/pw2userdb";

$redir="";

if ( $todir =~ /./ )
{
	$redir=">$todir/users-vpasswd";
	-d "$todir/domains" || mkdir("$todir/domains", 0700) || die "$!\n";
}

if ( -f "$vpopmailhome/users/vpasswd")
{
	$rc=system ("$bindir/pw2userdb --vpopuid --passwd='$vpopmailhome/users/vpasswd' --noshadow --nouid $redir");
	exit $rc / 256 if $rc;
}

if ( opendir(DIR, "$vpopmailhome/domains"))
{
	while ($domain=readdir(DIR))
	{
		$domainopt="--domain='$domain'";
		$domainopt="" if $domain eq "default";
		next if $domain eq "." || $domain eq "..";
		next unless -f "$vpopmailhome/domains/$domain/vpasswd";
		$redir="";
		if ( $todir =~ /./ )
		{
			$redir=">$todir/domains/$domain";
			$redir=">$todir/users-default"
				if $domain eq "default";
		}

		$rc=system ("$bindir/pw2userdb --passwd='$vpopmailhome/domains/$domain/vpasswd' --vpopuid --noshadow --nouid $domainopt $redir");

		exit $rc / 256 if $rc != 0;
	}
	close(DIR);
}

