#!/usr/bin/eperl
###
#
# Copyright (c) Ensim Corporation 2000, 2001   All Rights Reserved.
#
# This software is furnished under a license and may be used and copied
# only  in  accordance  with  the  terms  of such  license and with the
# inclusion of the above copyright notice. This software or any other
# copies thereof may not be provided or otherwise made available to any
# other person. No title to and ownership of the software is hereby
# transferred.
#
# The information in this software is subject to change without notice
# and  should  not be  construed  as  a commitment by Ensim Corporation.
# Ensim assumes no responsibility for the use or  reliability  of its
# software on equipment which is not supplied by Ensim.
#
# --------------------------------------------------------------------------
# $Id: create_mlist,v 1.1.1.1 2008-03-01 00:21:36 aarefyev Exp $
# $Name: not supported by cvs2svn $
# --------------------------------------------------------------------------
# create_mlist: Creates a new mailing list
# Usage: create_mlist <encoded args>
# -------------------------------------------------------

#push @INC, ($ENV{'OCW_SVCPATH'} || "/usr/lib/opcenter")."/apache";
push @INC, ($ENV{'OCW_SVCPATH'} || "/usr/lib/opcenter")."/cmdline_common";
push @INC, ($ENV{'OCW_SVCPATH'} || "/usr/lib/opcenter")."/sendmail";

require '/usr/lib/opcenter/cmdline_common/CmdLineCoder.pm';
require '/usr/lib/opcenter/majordomo/mymajordomo-lib.pl';
require '/usr/lib/opcenter/majordomo/majordomo.pm';
require '/usr/lib/opcenter/majordomo/ctime.pl';

use lib ($ENV{OCW_SVCPATH} or "/usr/lib/opcenter") . "/majordomo";
use lib ($ENV{OCW_SVCPATH} or "/usr/lib/opcenter") . "/cmdline_common";

use ERRORS;
use Carper;
use English;

sub GetSiteOwner {
  my (@retval) = ();
  @file_stat = lstat("/home");
  $uid = $file_stat[4];
  $gid = $file_stat[5];
  @retval = ($uid, $gid);
  return @retval;
}

sub GetOwnerAccess {
  my (@retval) = ();
  @retval = ($EFFECTIVE_USER_ID, $EFFECTIVE_GROUP_ID);
  return @retval;
}

sub DemoteOwnerAccess {
  my ($site_uid, $site_gid) = (0, 0);
  ($site_uid, $site_gid) = &GetSiteOwner();
  $EFFECTIVE_GROUP_ID = $site_gid;
  $EFFECTIVE_USER_ID = $site_uid;
}

sub PromoteOwnerAccess {
  my ($site_uid, $site_gid) = @_;
  $EFFECTIVE_USER_ID = $site_uid;
  $EFFECTIVE_GROUP_ID = $site_gid;
}

local $in;
local %in;
# Decode the string argument before performing any vodoo on it
&CmdLineCoder::decode_args();
$in = $ARGV[0];

#%access = &get_module_acl();
#$access{'create'} || &error("You are not allowed to create new lists");

# get the initial set configuration (includes the right majordomo paths etc)
$conf = &get_config();
$aliases_files = [$config{'aliases_file'}];

#$ldir = &perl_var_replace(&find_value("listdir", $conf), $conf);
$myos = &getMyOS();
if ($myos eq "Linux") { 
$ldir = '/var/lib/majordomo/lists';
$newalias_path= '/usr/bin/newalias';
}
else {
$ldir = '/usr/local/majordomo/lists';
$newalias_path= '/usr/local/etc/mail/newaliases';
}

# convert the form-parameters back into a dictionary structure from a string
%in = &majordomo::stringToDict($in);

# do our own validation for the parameters passed
local $err = &majordomo::validateInput(%in);

# Create list members file
local $name = $in{'name'};
if(&user_exists($name)) {
$cerr += $E_LISTNAMEEXISTS and $cerr += {list => $in{'name'} } ;
die "Mailing List \"$name\" already exists. \n";
}

if ( -f "$ldir/$in{'name'}") {
$cerr += $E_LISTEXISTS and $cerr += {list => $in{'name'} } ;
die "Mailing List \"$name\" already exists. \n";
}

local ($saved_uid, $saved_gid) = (0,0);
($saved_uid, $saved_gid) = &GetOwnerAccess();
# XXX Temporary hack for PRs 30490 and 30491
# uncomment when we make the /var/lib/majordomo directories
# owned by site admin again
#&DemoteOwnerAccess();

open(MEMS, ">$ldir/$in{'name'}");
close(MEMS);
&set_permissions("$ldir/$in{'name'}");

$whereami = `hostname -f`;

# Have majordomo create the new config file, by fooling the wrapper
# into thinking it has ==received an email with a config command
open(WRAPPER, "|$config{'program_dir'}/wrapper majordomo >/dev/null 2>&1");
print WRAPPER "From: site_blackhole\@$whereami\n\n";
print WRAPPER "config $in{'name'} $in{'name'}.admin\n\n";
close(WRAPPER);

#added for PR:32827 It's a workaround for setting the user enter password in the listname.config file. listname.config file is modified after it is created.
if (-f "$ldir/$in{'name'}.config")
   {
#    system("perl","-pi","-e","s/^[\\s\\t]*admin_passwd[\\s\\t]*=[\\s\\t]*[^\\s\\t]*\$/admin_passwd  = $in{'password'}/g","$ldir/$in{'name'}.config");
    $pass=$in{'password'};
    $pass=~s/\$/\\\$/g; # to escape error for password containing '$'
    $pass=~s/\//\\\//g; # to escape error for password containing '/'
    system("perl","-pi","-e","s/^[\\s]*admin_passwd[\\s]*=[\\s]*[\\S]+[\\s]*\$/admin_passwd = $pass\n/g","$ldir/$in{'name'}.config");
   }

# Added so that first config command will crated the list and mail will go to
# site_blackhole user and the second config command will return the already created
# (but altered config file with the new password) to the site admin. 
open(WRAPPER, "|$config{'program_dir'}/wrapper majordomo >/dev/null 2>&1");
print WRAPPER "From: root\@$whereami\n\n";
print WRAPPER "config $in{'name'} $in{'password'}\n\n";
close(WRAPPER);


&set_permissions("$ldir/$in{'name'}.config");

#create the intro file ( Welcome message)
open(INTRO,">$ldir/$in{'name'}.intro");
print INTRO $in{'introductoryMessage'};
close(INTRO)
&set_permissions("$ldir/$in{'name'}.intro");

# create the .info file
$lfile = "$ldir/$in{'name'}.config";
$list = &get_list_config($lfile);
chop($ctime = ctime(time()));
$updated = "[Last updated on: $ctime]\n";
open(INFO, ">$ldir/$in{'name'}.info");

if (&find_value("date_info", $list) eq "yes") {
	print INFO $updated;
	}
print INFO $in{'description'};
close(INFO);
&set_permissions("$ldir/$in{'name'}.info");
chomp($whereami);
# Create aliases for the new list

&PromoteOwnerAccess($saved_uid, $saved_gid);
&newlist_alias($in{'name'}, "\"|$config{'program_dir'}/wrapper ".
				       "resend -l $in{'name'} -h $whereami $in{'name'}-outgoing\"");
&newlist_alias($in{'name'}."-outgoing", ":include:$ldir/$in{'name'}");
&newlist_alias($in{'name'}."-list", ":include:$ldir/$in{'name'}");
&newlist_alias("owner-".$in{'name'}, $in{'owner'});
&newlist_alias($in{'name'}."-owner", $in{'owner'});
&newlist_alias($in{'name'}."-approval", $in{'owner'});
&newlist_alias($in{'name'}."-request", "\"|$config{'program_dir'}/wrapper ".
				       "majordomo -l $in{'name'}\"", 1);
&DemoteOwnerAccess();

# Update the new config file
&save_list_directive($list, $lfile, "description", $in{'description'});
&save_list_directive($list, $lfile, "admin_passwd", $in{'password'});
&save_list_directive($list, $lfile, "approve_passwd", $in{'password'});
&save_list_directive($list, $lfile, "message_footer", $in{'footer'}, 1);
&save_list_directive($list, $lfile, "restrict_post", "$ldir/$in{'name'}");
#&save_list_directive($list, $lfile, "moderate", $in{'moderate'});
#&save_list_directive($list, $lfile, "moderator",
#		     $in{'moderator_def'} ? "" : $in{'moderator'});
&flush_file_lines();

&PromoteOwnerAccess($saved_uid, $saved_gid);

open(EXCLIST, "> /etc/mail/majordomo-virtusertable");
local @mlist = &majordomo::list_lists($conf);
foreach $l (@mlist) {
  print EXCLIST "$l-list\@$whereami error:nouser User unknown\n";
  print EXCLIST "$l-outgoing\@$whereami error:nouser User unknown\n";
}
close(EXCLIST);
if (-f "/etc/mail/virtusertable") { 
  system("cat /etc/mail/virtusertable /etc/mail/majordomo-virtusertable | /usr/bin/makemap hash /etc/mail/virtusertable.db");
} else {
  system("/usr/bin/makemap hash /etc/mail/virtusertable.db < /etc/mail/majordomo-virtusertable");
}

#forcing the read of alis file after all the new aliases have eben written 
system("$newalias_path >/dev/null 2>&1");
sub newlist_alias()
{
    local $al = { 'name' => $_[0],
	          'values' => [ $_[1] ],
	          'enabled' => 1 };
    &majordomo::sendmail_call('create_alias', $al, $aliases_files);
}
sub user_exists
{
    my($name) = $_[0];
    my($str) = "";
    my($usrname) = "";
    my(@fields) ;
    my($found) = 0;
    open(PASSWD, "</etc/passwd") || die "Cannot open passwd file";
    while(<PASSWD>)
    {
	chomp;
	@fields = split /:/;
	$usrname = $fields[0];
	if($usrname =~ /^$name$/)
	{
	    $found = 1;
	}
    }
    close(PASSWD);
    return $found;
}

