#!/usr/bin/perl -w

use strict;

my %passwd_here;
my %passwd_new;

my $local_users = 0;
my $new_users = 0;
my $new_aliases = 0;

open(PI,"/etc/passwd") || die "can't open current passwd: $!";
while(<PI>) {
	chomp;
	my ($login,$passwd,$uid,$gid,$gecos,$rest) = split(/:/,$_,6);
	if (defined $passwd_here{$login}) {
		print "user $login ($gecos) is listed twice in local passwd";
	} else {
		$passwd_here{$login}=$gecos;
		$local_users++;
	}
}
close(PI);

open(PO,"> passwd.new") || die "can't open passwd.new: $!";
open(SO,"> shadow.new") || die "can't open shadow.new: $!";

open(PI,"passwd") || die "can't open input passwd: $!";
while(<PI>) {
	chomp;
	my ($login,$passwd,$uid,$gid,$gecos,$rest) = split(/:/,$_,6);

	$uid += 10000;	# all new uid's will be > 10000

	if ($passwd_here{$login}) {
		print "user $login ($gecos) allready exists in local passwd, skipping...\n";
	} else {
		# create home, imapd need it!
		my $home = "/var/webmail/home/$login";
		mkdir $home || die "can't create home dir $home: $!";
		chmod 0777,$home || die "can't chmod home $home to 777: $!";

		# /bin/true must be in /etc/shells or most services won't work!
		print PO "$login:x:$uid:100:$gecos:$home:/bin/true\n";
		print SO "$login:$passwd:12110:0:99999:7:::\n";
		$passwd_new{$login}=$gecos;
		$new_users++;
	}
}
close(PI);
close(PO);

open(AI,"aliases") || die "can't open aliases: $!";
open(AO,"> aliases.new") || die "can't open aliases.new: $!";
while(<AI>) {
	chomp;
	next if (/^\s*$/ || /^\s*#/);
	my ($alias,$account) = split(/\s*:\s*/,$_,2);
	if ($passwd_new{$account}) {
		print AO "$alias:\t$account\n";
		$new_aliases++;
	} else {
		# this will try to expand users on the right
		# it might be overkill, but hey! it might help also...
		if ($account =~ /,/) {
			my $all_local = 1;
			foreach my $login (split(/\s*,\s*/,$account)) {
				$all_local = 0 if (! $passwd_new{$login});
			}
			if ($all_local) {
				print AO "$alias\t$account\n";
				$new_aliases++;
			} else {
				# debug, verbose, remove...
				#print "skip: $alias -> $account\n";
			}
		}
	}
}
close(AI);
close(AO);

print "local users: $local_users\n";
print "new users: $new_users\n";
print "new aliases: $new_aliases\n";
