#!/usr/bin/perl -w
#----------------------------------------------------------------------
# copyright (C) 2000-2006 Gormand Pty Ltd
# copyright (C) 2002,2006 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::util;

use File::Find;
use User::pwent;

use Mail::Ezmlm;

my $conf = esmith::ConfigDB->open;
my $accounts = esmith::AccountsDB->open;

my $event = $ARGV [0];
die "event argument missing." unless defined ($event);

my $listName = $ARGV[1];
die "listName argument missing." unless defined ($listName) || $event eq "smeserver-ezmlm-web-update";

# We really want to do all ezmlm functions as the user ezmlm - saves
# lots of permissions fixups later on

unless (defined getpwnam("ezmlm"))
{
    system(qw(/usr/sbin/useradd -c EZMLM 
		-u 80 
		-d /home/e-smith/files/ezmlm
		-s /bin/false ezmlm)) == 0
	    or warn("Could not create user 'ezmlm'\n");

    $accounts->new_record("ezmlm", { type => "system", Uid => "80", Gid => "80" } )
	unless ($accounts->get("ezmlm"));
}

my $pw = getpwnam("ezmlm") or die "User ezmlm not found";
my $ownerHome = $pw->dir;

# XXX post-upgrade/init-accounts does chown root:root /home/e-smith/files/* 
# XXX and ezmlm needs to be able to write to its home directory
# XXX The permissions should be in the RPM spec file - just fix it for now
esmith::util::chownFile("ezmlm", "ezmlm",  $ownerHome);


if ( $event eq "smeserver-ezmlm-web-update" )
{
  my $ezmlm = new Mail::Ezmlm;
  # check default hostname
  my $thisdomain = $ezmlm->_getdefaultdomain;
  # fix perms
  my $listHomeBase="$ownerHome/lists";
  opendir(DIR, $listHomeBase)|| die "can't opendir $listHomeBase: $!";
  foreach my $listName ( grep { not /^\./ and -d "$listHomeBase/$_" } readdir(DIR) )
    {
    next unless $accounts->get($listName);
    my $listHost=$accounts->get($listName)->prop("Domain");
    my $listHome="$listHomeBase/$listName";
    my $dotQmail = ".qmail-${listName}";
    my $listAlias = "${ownerHome}/${dotQmail}";
    # fix file perms
    fixperms($listHost,$thisdomain,$listHome,$listName);
    # fix list version
    if (-f "$listHome/flags")
      {
	$ezmlm->setlist("$listHome");
	my $flags = $ezmlm->_getconfig_idx5();
	$flags =~  s/[CV]//ig;
 	print "$flags\n";
	$ezmlm->update($flags);# or die $ezmlm->error();
      }
    }
  # delete broken .qmail links
  opendir(DIR, $ownerHome)|| die "can't opendir $ownerHome: $!";
  foreach my $link (readdir DIR) {
    next unless -l "$ownerHome/$link" and not -e readlink("$ownerHome/$link");
    print "Removing broken link $link\n";
    unlink "$ownerHome/$link" or die "Can't delete '$link': $!";;
  closedir(DIR);
  }
  
 exit 0
} 


$> = $pw->uid;
$) = $pw->gid;

my $list = $accounts->get($listName) or die "$listName not found in accounts db";
die "$listName is not a mailing list account." 
	unless ($list->prop('type') eq "mailinglist");

my $listHost = $list->prop("Domain");

my $listHomeBase = "${ownerHome}/lists";

mkdir $listHomeBase, 0700 unless (-d $listHomeBase);

my $listHome = "${listHomeBase}/${listName}";

my $dotQmail = ".qmail-${listName}";

my $listAlias = "${ownerHome}/${dotQmail}";

if ( $event eq "mailinglist-create" )
{
    my $ezmlm = new Mail::Ezmlm;
    
    my $thislist = $ezmlm->make(
		-dir      => $listHome,
                -qmail    => $listAlias,
                -name     => $listName,
                -host     => $listHost,
                -user     => '',
                -switches => 'aBdfgHiJklMnOpQrStuWx',
		);

    die "List creation failed\n" unless $thislist;

    my $listOwner = $list->prop("Owner");

    $ezmlm->update("5 $listOwner");
}
elsif ( $event eq "mailinglist-delete" )
{
  # Remove the .qmail files for this list
  #$> = 0;
  #$) = 0;
  for ( readdir(DIR) )
    {
    unlink "$ownerHome/$_" if /^$dotQmail$/ ||
        /^$dotQmail-accept-default$/ ||
        /^$dotQmail-default$/ ||
        /^$dotQmail-digest-owner$/ ||
        /^$dotQmail-digest-return-default$/ ||
        /^$dotQmail-owner$/ ||
        /^$dotQmail-reject-default$/ ||
       /^$dotQmail-return-default$/;
    }
  closedir(DIR);
  # And the list management directory
  system( '/bin/rm', '-rf', $listHome ) ==0 or 
	die "Couldn't remove list directory $listHome";
}
elsif ( $event eq "mailinglist-modify" )
{
  my $ezmlm = new Mail::Ezmlm;
  # check default hostname
  my $thisdomain = $ezmlm->_getdefaultdomain;
  # update /create inlocal if needed.
  $> = 0;
  $) = 0;
  fixperms($listHost,$thisdomain,$listHome,$listName);

}
else
{
    die "Couldn't work out function to call for $0";
}

#==============================================================
# fix ml perms and needed files
#==============================================================
our @content;
our $search="";
sub fixperms
{
  my $listHost = shift;
  my $thisdomain = shift;
  my $listHome = shift;
  my $listName = shift;

  if ( "$listHost" ne "$thisdomain")
    {
      open(INLOCAL, ">$listHome/inlocal");
      print INLOCAL "$listName\n";
      close INLOCAL;
    }
  # check all file in folder are "ezmlm", "admin" 
  my @readread= qw(archnum inlocal mimeremove num  prefix webnames);
  opendir(DIR, $listHome) || die "can't opendir $listHome: $!";
  for $a ( grep { not /^\./ } readdir(DIR) )
    {
      esmith::util::chownFile("ezmlm", "admin",  "$listHome/$a");
      if ( -d "$listHome/$a" )
        {
        chmod 0700, "$listHome/$a";
        }
      elsif ( $a ~~ @readread)
        {
        chmod 0644, "$listHome/$a";
        }
      else
        {
       chmod 0600, "$listHome/$a";
        }
    }
  closedir DIR;
  # all archives subfolder and files "ezmlm", "ezmlm"
  @content=();
  $search="$listHome/archive"; find( \&wanted, $search);
  $search="$listHome/bounce"; find( \&wanted, $search);
  map {esmith::util::chownFile("ezmlm","ezmlm",$_) } @content;
}
sub wanted  {
    push @content, $File::Find::name unless $File::Find::name eq $search;
    return;
}
