#!/usr/bin/perl
#
# Morikawa Yasuhiro	2002.04.28
#
# Kyoma TAKAHASHI	1999.7.9
#			1999.10.02
# Thanks for Toyoda's help.

#
# imappwdbg - imap $BMQ%Q%9%o!<%I%U%!%$%k@8@.%9%/%j%W%H(B
#
# $B!&(B $B35MW(B
#
#    $B0lHL%f!<%6$N(B ~/Maildir/.password $B$K5-=R$5$l$k%Q%9%o!<%I$r(B
#    /etc/cram-md5.pwd $B%U%!%$%k$KNs5s$9$k(B.
#

    # $BMxMQ$9$k%3%^%s%I(B
$chmodbin = '/bin/chmod';
$usershow = '/usr/local/bin/gate-user-show';

    # $BMxMQ$9$k%U%!%$%k(B
$imappwdb = '/etc/cram-md5.pwd';
$userpwfile = 'Maildir/.password';


    # cram-md5.pwd $B$K=q$-9~$_$G$-$k$h$&$K(B
    # $B%Q!<%_%C%7%g%s$rJQ99(B
system "$chmodbin 600 $imappwdb";

open(DBFILE,"> $imappwdb");

    # cram-md5.pwd $B$N;O$a$K%3%a%s%H$r=q$-=P$9(B.
print DBFILE '# CRAM-MD5 authentication database',"\n";
print DBFILE '# Entries are in form <user><tab><password>',"\n";
print DBFILE '# Lines starting with "#" are comments',"\n";
print DBFILE "\n";

while (($user,$passwd,$uid,$gid,$quota,$comm,$gcos,$dir) = getpwent) {
    #
    # $B0lHL%f!<%6$N(B .password $B$N$_;2>H$9$k(B
    # 
    if ( $uid >= 1000 && $uid <= 29999 ) {
	open(PWFILE,"< $dir/$userpwfile");
	$pass = '';
	$pass = $_ while(<PWFILE>);
	chop($pass);
	close(PWFILE);
	if($pass ne '') {
	    #
	    # gate-user-show $B$rMxMQ$7$F(B, $B8D?M%f!<%6$+(B
	    # $B%0%k!<%W%f!<%6$+H=JL$9$k(B
	    #
	    unless (-x $usershow) {
		die "imappwdbg require $usershow\.\n"
		    ."Please install gate-toroku-system\.\n";
	    }
	    open (GATEUS,"$usershow $user |");
	    while (<GATEUS>) { 
		if (/type/) { ($typeq) = /type: (.*)/; } 
	    }
	    close (GATEUS);
	    #
	    # $B%0%k!<%W%f!<%6$N>l9g$OL5;k(B
	    #
	    if ( $typeq eq 'person' ) {
		print DBFILE $user;
		print DBFILE "\t";
		print DBFILE $pass;
		print DBFILE "\n";
	    }
	}
    }
}

close(DBFILE);

    # cram-md5.pwd $B$r=q$-9~$_IT2D$K$7$F$*$/(B
system "$chmodbin 400 $imappwdb";
