#!/bin/sh
#
# Copyright (c) 1999-2008 Parallels
# All rights reserved
#

#
# Plesk script
#


p_echo()
{
[ -z "$product_log" ] || echo "$@" >> "$product_log" 2>&1
echo "$@"
}

simply_die()
{
	report_problem "$@"
	exit 1
}

# Use this function to report failed actions.
# Typical report should contain
# - reason or problem description (example: file copying failed)
# - how to resolve or investigate problem (example: check file permissions, free disk space)
# - how to re-run action (example: perform specific command, restart bootstrapper script, run installation again)
report_problem()
{
	p_echo
	if [ $problems_occured -eq 0 ]; then
		echo "***** $process problem report *****" >> "$product_problems_log" 2>&1
	fi
	for problem_message in "$@"; do
		p_echo "$problem_message"
		echo "$problem_message" >> "$product_problems_log" 2>&1
	done
	p_echo

	problems_occured=1
}

detect_vz()         
{                   
    local vzcheck_file
        
    PLESK_VZ=0
    vzcheck_file="/proc/self/status"
                    
    if [ ! -f ${vzcheck_file} ]; then
        return 1; 
    fi              
                    
    grep -q -E '^envID\:[[:space:]]*([[:digit:]]+)$' < ${vzcheck_file} >/dev/null 2>&1
                    
    if [ $? -eq 0 ]; then
        PLESK_VZ=1  
        return 0;
    fi      
    return 1;
}

#set_params

set_common_params()
{
	common_var=0

	PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
	LANG=C
	export PATH LANG
	umask 022
	ulimit -n 65535 2>/dev/null

	K_HUP="/bin/kill -HUP"
	K_KILL="/bin/kill -KILL"
	K_TERM="/bin/kill -TERM"
	K_USR2="/bin/kill -USR2"

	users_created=""
	groups_created=""

	certificate_file="$PRODUCT_ETC_D/httpsd.pem"
	services="/etc/services"
	mtab="/etc/mtab"
	[ -f "/etc/rsyslog.conf" ] && syslog_conf="/etc/rsyslog.conf" || syslog_conf="/etc/syslog.conf"
	syslog_conf_ng="/etc/syslog-ng/syslog-ng.conf"
	get_hostname="hostname"
	get_domainname="domainname"

	#VZP used to determine that we're inside SVE
	vza_file="/var/vzagent"

	#default parameters
	tar="tar"
	crontab="/usr/bin/crontab"

	cp_preserve="cp -p"
	SYSTEM_RC_D=/etc/init.d
	PLESK_LIBEXEC_DIR="/usr/lib/plesk-9.0"
	PLESK_DB_DIR="/var/lib/plesk"
	POSTFIX_LIBEXEC_DIR="/usr/lib/postfix"
	PRODUCT_BOOTSTRAPPER_DIR="/opt/psa/bootstrapper/pp10.8.0-bootstrapper"

	set_common_params_linux 

	detect_vz
}

set_common_params_linux()
{
	get_hostname="hostname -f"
	fstab="/etc/fstab"
	cp_preserve="cp --preserve=all --remove-destination"
	machine="linux"
	sendmail="/usr/sbin/sendmail"
	ps="ps axw"
	ps_long="ps axuw"
	false_shell="/bin/false"
	dummy_home="/"
	compress="gzip -9 -c"
	uncompress="gunzip -c"
	uudecode="uudecode -o /dev/stdout"
	ifconfig="/sbin/ifconfig -a"
	inet_str="inet addr"

	if [ -f /etc/slackware-version ]; then
	    linux_distr="slackware"
	    useradd_options=""
	    sndml_ini="/etc/rc.d/init.d/sendmail"
	    mail_local="/usr/libexec/mail.local"
	    dummy_shell=""
	    named_osrelease=0
	else
	    useradd_options="-M"
	    if [ -f /etc/mandrake-release ]; then
		linux_distr="mandrake"
	    elif [ -f /etc/fedora-release ]; then
		linux_distr="fedora"
	    elif [ -f /etc/SuSE-release ]; then
		linux_distr="suse"
	    elif [ -f /etc/debian_version ]; then
		linux_distr="debian"
		get_domainname="dnsdomainname"
		useradd_options=""
	    else
		linux_distr="redhat"
	    fi

	    sndml_ini="/etc/init.d/sendmail"
	    mail_local="/usr/libexec/mail.local"
	    if [ -x /sbin/nologin ]; then
		dummy_shell="/sbin/nologin"
	    else
		dummy_shell="/bin/false"
	    fi
	    bash_shell="/bin/bash"
	    rbash_shell="/bin/rbash"
	    uudecode_full="/usr/bin/uudecode"
	    named_osrelease=`cat /proc/sys/kernel/osrelease | perl -F"/[.-]/" -n -a  -e 'printf "%02u%02u%02u\n", $F[0],$F[1],$F[2]'`
	fi

	return 0
}
# -*- shell-script -*-
# configures Mailman to use a given mailserver
# Currently Postfix and QMail, both as "Manual" (see comments below)
set_mailman_mailsrv()
{
    local cfg server

    cfg=$1
    server=$2

    if [ -z "$cfg" ]; then
        simply_die "Usage: $0 /path/to/mm_cfg.py (qmail|postfix)"
    fi

    case "$server" in
        qmail)
            server="Manual"
            ;;
        postfix)
            # Although Mailman supports Postfix "directly" (i.e. it has
            # a code to control Postfix system aliases (typically, /etc/aliases)
            # we keep Mailman related system aliases in an additional hashed
            # database (hash:/var/spool/postfix/plesk/aliases)
            # (for various reasons), so we have to manage Mailman-specific alias
            # manually as with QMail
            server="Manual"
            ;;
        *)
            simply_die "Currently only qmail and postfix are supported"
            ;;
    esac

    if [ ! -f "$cfg" ]; then
        simply_die "Usage: no such file or directory \"$cfg\""
    fi

    #declare pymod pydir curmta
    local pydir pymod
    pydir=$(dirname "$cfg")
    [ -z "$pydir" ] && pydir="."
    pymod=$(basename "$cfg")
    pymod=${pymod%%.py}

    local python_bin
    python_bin="/usr/bin/python2.5"

    local currentServer
    currentServer=$(PYTHONPATH="${PYTHONPATH}:$pydir" "${python_bin}" -c "import $pymod; print $pymod.MTA")
    if [ $? -ne 0 ]; then
        simply_die "Unable to load current settings"
    fi

    if [ "x${currentServer}" = "x${server}" ]; then
        # nothing to do
        return 0
    fi

    local tmpcfg bakcfg

    bakcfg="${cfg}.saved_by_plesk"
    tmpcfg=$(mktemp "${cfg}.XXXXXX")
    if [ $? != 0 ]; then
        simply_die "Unable to creare a temporary file for ${cfg}"
    fi
    trap "mailman_trap_handler \"$tmpcfg\"" HUP PIPE INT TERM EXIT
    awk -v server="$server" 'BEGIN { found=0; }
/^[[:space:]]*MTA[[:space:]]*=/ {
    print "### ", $0;
    if (!found) {
        str=$0;
        sub(/=.*/, "='"'"'" server "'"'"'", str);
        $0=str;
        found=1;
    }
}
{ print $0; }
END {
    if (!found) {
        print "MTA='"'"'" server "'"'"'";
    };
    exit 0;
}' "$cfg" >>"$tmpcfg"
    rc=$?
    if [ 0 -eq $rc ]; then
        p_echo "updating configuration file $cfg"
        rm -f "$bakcfg" 2>/dev/null; # errors will be reported later
        ln "$cfg" "$bakcfg" &&             mv -f "$tmpcfg" "$cfg" || simply_die "unable to save new configuration"
        rm -f "$tmpcfg"
        trap - HUP PIPE INT TERM EXIT
    else
        simply_die "unable to process \"$cfg\""
    fi
    return 0
}

# This function tries to configure Plesk-specific
# wrapper (mm_wrapper) which ensures that
# /usr/lib/mailman/mail/mailman will be called with
# the correct group.
# The problem is that on RH* and derivatives
# /usr/lib/mailman/mail/mailman should be called
# from within a process with one of the following groups:
# mail, nobody, postfix, daemon
# while on SuSE this should be a group whose gid is
# stored in either /etc/mailman/mailman.mail-gid or
# /etc/mailman/mailman.cgi-gid. This group must to be
# coincide with GID for postfix-mailman process from
# postfix master.cf config file.
# So if the file /etc/mailman/mailman.mail-gid exist
# we ensure that it contains an appropriate gid and
# change the file if needed (preserving a backup)
# If the file is missing then we make sure that
# mm_wrapper is SGID mail.
#
# Requirements: coreutils, grep, sed, perl

set_mailman_wrapper_perms()
{
    local mm_wrapper initial_group gidfiles backup

    mm_wrapper=/usr/lib/plesk-9.0/mm_wrapper
    initial_group=popuser
    gidfiles="/etc/mailman/mailman.mail-gid /etc/mailman.mail-gid"
    backup=.saved_by_psa

	[ -f "$mm_wrapper" ] || return

    local mm_wrapper_group

    if mailman_isSGID "$mm_wrapper" ; then
        mm_wrapper_group=$(mailman_getFGID "$mm_wrapper")
    else
        mm_wrapper_group=$(mailman_getGNam "$initial_group")
    fi

    [ -z "$mm_wrapper_group" ] && simply_die "unable to get current mm_wrapper group"

    # Now check the style of operation
    hasGidfile=0;
    for gidfile in $gidfiles; do
        if [ -r "$gidfile" ]; then
            if [ x$(cat "$gidfile") != x$mm_wrapper_group ]; then
                cp -pr "$gidfile" "$gidfile$backup" || simply_die "Unable to create a backup file";
                echo -n "$mm_wrapper_group" > "$gidfile";
            fi;
            hasGidfile=1;
        fi;
    done;

    if [ $hasGidfile = 0 ]; then
        # need to "hardcode" the SGID group
	if [ "X$machine" = "XBSD" ]; then
		chown :list "$mm_wrapper"
	else
		chown :mail "$mm_wrapper"
	fi
        chmod g+s "$mm_wrapper"
    fi
    return 0
}

# 1st check if the mm_wrapper is SGID
mailman_isSGID() {
    # Does it really work? ;-)
    ! perl -e "exit(-g \"$1\");"
}

# stat has different options in Linux and in
# other supported systems
mailman_getFGID()
        { stat -c%g "$1"; }

# hack! hack! hack!
mailman_getGNam()
    { grep "^$1:" /etc/group | cut -f 3 -d ':'; }

mailman_trap_handler()
{
    trap - EXIT
    rm -f -- "$1"
    exit
}
# -*- shell-script -*-
# A quick script to fix MTA configuration setting in
# Mailman configuration file /path/to/mm_cfg.py

# Usage: mailman_conf_init /path/to/mm_cfg.py
# Requirements: coreutils, awk, python
if [ -z "$1" ]; then
    echo "Usage: $0 /path/to/mm_cfg.py"
    exit 1
fi

# do not use plesk shell lib die, it's too hairy
if ! set_mailman_mailsrv "$1" qmail; then
    echo "unable to configure Mailman to work with QMail"
	exit 1
fi

set_common_params
if ! set_mailman_wrapper_perms; then
    echo "unable to set Mailman wrapper permissions"
	exit 1
fi
