#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 1999-2005 Mitel Networks Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#
#----------------------------------------------------------------------

package esmith;

use strict;
use Errno;
use esmith::ConfigDB;
use esmith::AccountsDB;
use esmith::templates;
use User::pwent;


my $accountsdb = esmith::AccountsDB->open_ro or
    die "Could not open accounts db\n";

my $event = shift;
my $userName = shift;
my @users;

if (defined $userName)
{
    my $user = $accountsdb->get($userName);
    die
	"Account $userName is not a user account; update email forwarding failed.\n"
	unless $userName eq 'admin' || ($user && $user->prop('type') eq "user");
    @users = ($user);
}
else
{
    @users = ( $accountsdb->users, $accountsdb->get('admin') );
}

foreach my $user (@users)
{
    my $userName = $user->key;

    setpwent();
    my $home = getpwnam($userName)->dir;
    for my $dotfile ( qw(.qmail .qmail-junkmail) )
    {
        esmith::templates::processTemplate (
	{
	    MORE_DATA			=>
		{
		    USERNAME => $userName ,
		},
	    TEMPLATE_PATH		=> "/$dotfile",
	    TEMPLATE_EXPAND_QUEUE	=>
		[
		    "/etc/e-smith/templates-user-custom",
		    "/etc/e-smith/templates-user",
		],
	    OUTPUT_PREFIX		=> "$home",
	    UID				=> $userName,
	    GID				=> $userName,
	    PERMS			=> 0644,
        } );
    };
    unless (-f "$home/.qmail-default")
    {
	symlink ".qmail", "$home/.qmail-default";
    }
}

exit (0);
