#!/usr/local/bin/perl
#
# remove clear test passwords from all vpasswd files. make backups of
# original files.
#
# will only work if vpopmail was compiled with clear text password option.
#

use strict;
my %paths;

open(A, '/var/qmail/users/assign') || die "cannot open assign: $!\n";
while(<A>){
   if(/^\+[^:]+-:([^:]+):\d+:\d+:([^:]+):/){
		if((-f "$2/vpasswd") && (! -l $2)){
			$paths{$1} = $2;
		}
   }
}
close A;

while(my($domain,$dir) = each %paths){
	print "working on $domain\n";
	open(V, "${dir}/vpasswd") || die "cannot open $dir/vpasswd: $!\n";
	open(C, ">/tmp/vpopmail/$domain.vpasswd") || die "cannot write to /tmp/vpopmail/$domain.vpasswd: $!\n";
	open(N, ">${dir}/vpasswd.tmp") || die "cannot write to $dir/vpasswd.tmp: $!\n";
	my $n=0;
	while(<V>){
		print C;
		chomp(my $line = $_);
		$n++;
		if($line =~ /^([^:]+):([^:]+):(\d+):(\d+):([^:]*):([^:]+):([^:]+):/){
			my ($user,$crypt,$id,$gid,$comment,$maildir,$quota) = ($1,$2,$3,$4,$5,$6,$7);
	
			print N "${user}:${crypt}:${id}:${gid}:${comment}:${maildir}:${quota}\n";
		}else{
			print "unknown syntax in file (line $n)\n";
			print N "${line}\n";
		}
	}
	close N;
	close V;
	close C;
	if(rename("${dir}/vpasswd.tmp","${dir}/vpasswd")){
		unlink("${dir}/vpasswd.cdb") || warn "cannot delete $dir/vpasswd.cdb: $!\n";
	}else{
		warn "cannot rename $dir/vpasswd.tmp: $!\n";
	}
}
