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

#
# Plesk script
#

set_apache_params()
{
	apache_user="wwwrun"
	apache_UID=80
	apache_group="www"
	apache_GID=80

	user_apxs="/usr/sbin/apxs2"

	set_apache_params_linux

	apache_service="$apache_service_name"

	apache_httpd_conf="$HTTPD_CONF_D/httpd.conf"
	apache_httpd_conf2="$HTTPD_CONF_D/httpd2.conf"
	apache_httpd_conf_in="$HTTPD_CONF_D/httpd.conf.in"

	apache_httpd_include="$HTTPD_INCLUDE_D/zz010_psa_httpd.conf"

	APACHE_CERT="$HTTPD_CONF_D/httpd.pem"
	APACHE_ROOT="/usr"

	min_suexec_UID=10000
	max_suexec_UID=16000
	min_suexec_GID=$min_suexec_UID
	max_suexec_GID=$max_suexec_UID

	suexec_storage=/usr/local/psa/suexec
	suexec=/usr/sbin/suexec2
	suexec_dir=/usr/sbin
	suexec_file=suexec2

	rpm_httpd_bin=/usr/sbin/httpd
}

set_apache_params_linux()
{
	apache_pid_file="$APACHE_ROOT/logs/httpd.pid"
	apache_lock_file="$APACHE_ROOT/logs/httpd.lock"
	product_lock_file="$HTTPD_CONF_D/cnf.lock"
	apache_service_name="apache2"

	apache_modules_d="/usr/lib/apache2"
}

remove_tmp_state()
{
	if [ -d "/tmp/.state" ]; then
		rm -Rf "/tmp/.state" >> $product_log 2>&1
	fi
}


#courier-imap

set_courier_imap_params()
{
	IMAPD_CERT="/usr/share/courier-imap/imapd.pem"
	POP3D_CERT="/usr/share/courier-imap/pop3d.pem"

	courier_service="courier-imap"
}

# db_test test_query awk_script
# Runs test_query and processes it with awk_script. If the output is
# not empty, return 0, otherwise return 1. Hint: supply '1' for
# awk_script to test just for the presence of any output.
db_test()
{
	local any_db=
	eval `sh_get_args '--any-db) any_db=yes;;'`

	local test_query="$1"
	local awk_script="$2"

	if [ -n "$any_db" ]; then
		local output="`mysql_raw_anydb -e \"$test_query\" 2>>\"$product_log\"`"
	else
		local output="`mysql_raw -e \"$test_query\" 2>>\"$product_log\"`"
	fi
	local status=$?
	if [ "$status" -ne 0 ]; then
		p_echo "$output"
		die "run the following SQL query: $1"
	fi

	echo -n "$output" | awk -F '\t' -- "$awk_script" | test `wc -l` -ne 0
}

proftpd_super_server_config()
{
	local action="$1"

	case "$superserver" in
	    inetd)
		    ftp_rec="ftp stream tcp nowait root $PROFTPD_ROOT/sbin/proftpd proftpd -c $PROFTPD_ETC_D/proftpd.conf"
		    ;;
	    xinetd)
		    ftp_rec="service ftp
{
	socket_type		= stream
	protocol		= tcp
	wait			= no
	disable			= no
	user			= root
	instances		= UNLIMITED
	server			= $PROFTPD_ROOT/sbin/proftpd
	server_args		= -c $PROFTPD_ETC_D/proftpd.conf
}"
		    ;;
	    *)
		    die "Super server name unknown"
		    ;;
	esac

	super_server_action "$action" ftp "$ftp_rec"
}
# Usage:  pleskrc <service> <action>
pleskrc()
{
	[ 2 -le $# ] || die "Not enough arguments"

	local service_name=$1
	local action=$2
	local ret=0
	local inten
	local service_script
	shift
	shift

	# Now check redefined functions
	if test "$machine" = "linux" && is_function "${service_name}_${action}_${machine}_${linux_distr}"; then
		"${service_name}_${action}_${machine}_${linux_distr}" $@
		return $?
	elif is_function "${service_name}_${action}_${machine}"; then
		"${service_name}_${action}_${machine}" $@
		return $?
	elif is_function "${service_name}_${action}"; then
		"${service_name}_${action}" $@
		return $?
	fi

	# Not redefined - call default action
	eval "service=\$${service_name}_service"
	[ -n "$service" ] || die "Empty service name for $service_name"

	inten="$action service $service"
	[ "$action" = "status" -o "$action" = "exists" ] || echo_try "$inten"

	if [ -x  "$SYSTEM_RC_D/$service" ]; then
		service_script="$SYSTEM_RC_D/$service"
	elif [ ! -z ${PRODUCT_RC_D} -a -x "$PRODUCT_RC_D/$service" ]; then
		service_script="$PRODUCT_RC_D/$service"
	fi

	if [ "$action" = "exists" ]; then 
		[ -n "$service_script" ] && return 0 || return 1
	else
		[ -z "$service_script" ] && die "Unable to handle $service"
	fi


	if [ -x "/usr/sbin/invoke-rc.d" ]; then
		action_cmd="/usr/sbin/invoke-rc.d $service"
	elif [ -x "/sbin/service" ]; then
		action_cmd="/sbin/service $service"
	elif [ -n ${service_script} ]; then
		action_cmd="$service_script"
	fi


	case "$action" in
		start)
			pleskrc $service_name status || $action_cmd $action $@
			;;
		stop)
			if pleskrc $service_name status; then
				$action_cmd $action $@
			else
				true
			fi
		    ;;
		restart)
			if pleskrc $service_name status; then 
				$action_cmd "restart" $@
			else 
				$action_cmd "start" $@
			fi
		    ;;
		reload)
		    if pleskrc $service_name status; then
				$action_cmd "reload" $@
			else
				true
			fi
		    ;;
		status)
		    $action_cmd "status"
		    ;;
	    *)
		    $action_cmd $action $@ 
		    ;;
	esac

	ret="$?"
	if [ "$action" != "status" ]; then
		[ "$ret" -eq 0 ] && suc || warn $inten
	fi

	return $ret
}

is_function()
{
	local type_output="`LANG=C LC_ALL=C LC_MESSAGES=C type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			return 0
		;;
		*)
			return 1
		;;
	esac
}

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

pnnl_echo()
{
    echo -n "$*" >> "$product_log" 2>&1
    echo -n "$*" 
}

die()
{
	PACKAGE_SCRIPT_FAILED="$*"

	if [ "X$trigger_uninstall" != "X1" ]; then
		printf "\a\a"
		p_echo
		p_echo "ERROR while trying to $*"
		echo "Check the error reason(see log file: ${product_log}), fix and try again"
		p_echo
		if [ "X$do_patch" != "X1" -a "X$do_reconfigure" != "X1" ]; then
			p_echo "Aborting..."
			p_echo
		fi
	fi

	smart_undo_install

	selinux_close

	exit 1

}

warn()
{
local inten
inten="$1"
p_echo
p_echo "WARNING!"
pnnl_echo "During the $inten found some problems"
echo "(see log file: ${product_log})"
p_echo
p_echo "Continue..."
p_echo

}

echo_try()
{
	msg="$*"
	pnnl_echo " Trying to $msg... "
}

suc()
{
	p_echo "done"
}

mk_backup()
{
	target="$1"
	dup="$2"
	opts="$3"

	if [ -L "$target" ]; then
		rm "$target"
	elif [ -$opts "$target" ]; then
		if [ ! -$opts "$target.$product_suffo" ]; then
			case "$dup" in
				mv)
					mv -f $target $target.$product_suffo || die "mv -f $target $target.$product_suff"
					;;
				cp)
					cp -fp $target $target.$product_suffo || die "cp -fp $target $target.$product_suff"
					;;
				*)
					p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'"
					die "mk_backup"
					;;
			esac
		else
			case "$dup" in
				mv)
					mv -f $target $target.$product_suff || die "mv -f $target $target.$product_suff"
					;;
				cp)
					cp -fp $target $target.$product_suff || die "cp -fp $target $target.$product_suff"
					;;
				*)
					p_echo " mk_backup: wrong option -- must be 'cp' or 'mv'"
					die "mk_backup"
					;;
			esac
		fi
	else
		case "$opts" in
			f|d)
				;;
			*)
				p_echo " mk_backup: wrong option -- must be 'f' or 'd'"
				die "mk_backup"
				;;
		esac
	fi
}       

call_optional_function()
{
	export LANG=C LC_MESSAGES=C LC_ALL=C
	local type_output="`type \"$1\" 2>/dev/null | head -n 1`"
	case "$type_output" in
		*function)
			"$@"
			;;
		*)
			return 0
			;;
	esac
}

sh_get_args()
{
	echo 'while true; do case "$1" in '"$1"'*) break;; esac; shift; done'
}

configure_xinetd_compat()
{
	local inten="configure xinetd compatibility mode with $superserver"
	if [ "$linux_distr" = "debian" -o "$linux_distr" = "ubuntu" ]; then
		[ "$superserver_service" = "xinetd" ] || return 1
		[ -f "/etc/default/xinetd" ] || return 1
		grep -q 'XINETD_OPTS=.*-inetd_compat' /etc/default/xinetd && return 1
		echo_try $inten

		if ! grep -q '^\s*XINETD_OPTS' /etc/default/xinetd; then
			echo 'XINETD_OPTS="-inetd_compat"' >>/etc/default/xinetd
			suc
			return 0
		fi

		eval `grep '^\s*XINETD_OPTS' /etc/default/xinetd`
		XINETD_OPTS="$XINETD_OPTS -inetd_compat"
		local tmp_file=`mktemp /tmp/xinetdXXXXXX`
		sed -e "s/XINETD_OPTS.*/XINETD_OPTS=\"$XINETD_OPTS\"/g" /etc/default/xinetd > $tmp_file && mv -f $tmp_file /etc/default/xinetd
		suc
		return 0
	fi
	return 1
}


super_server_action()
{
    local in out
    local action="$1"
    local service="$2"
    local template="$3"

    inten="$action $service service record for $superserver_service daemon"

    case "$action" in
	remove) ;;
	register)
		[ -z "$template" ] && die "Template for super server $action was not defined"
		;;
	comment|disable)
		;; 
	configure)
		case "$superserver_mode" in
		    native)
			register_service $superserver_service defaults defaults
			;;
		    compat)
			configure_xinetd_compat && pleskrc superserver restart
			;;
		    *)
			die "Mode for $superserver_service was not defined"
			;;
		esac

		return 0
		;;
	*)
		die "Some arguments was not defined or defined incorrect for action with super server"
		;;
    esac 

    case "$superserver" in
	inetd)
		super_server_modify_inetd "$service" "$action" "$template"
		;;
	xinetd)
		super_server_modify_xinetd "$service" "$action" "$template"
		;;
	*)
		die "Unable to define super server type"
		;;	
    esac

    if [ $? -ne 0 ]; then
	die $inten 
    fi
}

super_server_modify_inetd()
{
	local service="$1"
	local action="$2"
	local template="$3"

	case "$action" in
		comment|disable)
			grep -q "^$service[[:space:]]" $superserver_conf || return 0
			sed -e "s|^$service|#$service|g" < "$superserver_conf" > "$superserver_conf.tmp" 			&& mv -f "$superserver_conf.tmp" "$superserver_conf" 			|| return 1
			;;
		remove)
			if [ -x /usr/sbin/update-inetd ]; then
				/usr/sbin/update-inetd --enable "$service"
				/usr/sbin/update-inetd --remove "$service"
			else
				grep -q "^$service[[:space:]]" $superserver_conf || return 0
				sed -e "s|^$service[[:space:]].*||g" < "$superserver_conf" > "$superserver_conf.tmp" 			    	&& mv -f "$superserver_conf.tmp" "$superserver_conf" 			    	|| return 1
			fi
			;;
		register)
			if [ -x /usr/sbin/update-inetd ]; then
				/usr/sbin/update-inetd --enable "$service"
				/usr/sbin/update-inetd --remove "$service"
				/usr/sbin/update-inetd --add "$template"
			else
				egrep -q "$template" $superserver_conf
				if [ "$?" -ne "0" ]; then 
					super_server_modify_inetd comment $service && 					echo "$template" >> $superserver_conf || return 1
				fi
			fi
			;;
	esac

	return 0
}

super_server_modify_xinetd()
{
	local file
	local service="$1"
	local action="$2"
	local template="$3"

	for file in $superserver_dir/*; do
		grep -q "$service" $file 1>$product_log 2>&1 || continue

		case "$action" in
		    remove)
			    awk "/^[[:space:]]*(#|[[:space:]])*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ 				{next;} {print}
			    " <$file >$file.tmp 			    && mv -f $file.tmp $file || return 1
			    ;;
		    comment)
			    awk "/^[[:space:]]*service[[:space:]]+$service($|[[:space:]]+)/,/.*}.*/ 			       { print \"#\"\$0; next; }
			       {print}
			    " < $file > $file.tmp 			    && mv -f $file.tmp $file || return 1
			    ;;
		esac
	done

	case "$action" in
	    register)
		    echo "$template" > "$superserver_dir/${service}_psa" || return 1
		    ;;
	    disable)
			[ -f "$superserver_dir/${service}_psa" ] && mv -f "$superserver_dir/${service}_psa" "$superserver_dir/${service}.psa"
		    ;;
	esac

	return 0
}

get_pid()
{
	local i

	local ex_f="$1"
	local opt="$2"
	local owner="$3"

	local min_num="1"

#	Use pidof by default, bug 121868, except for FreeBSD - 140182
	if type pidof >/dev/null 2>&1 && [ "$os" != "BSD" ]; then
		for pid in `pidof -o $$ -o $PPID -o %PPID -x $ex_f`; do
#	Check for owner
			[ "$opt" = "true" -a "$owner" != "`ps -p $pid -o ruser=`" ] && continue
			min_num=$pid
			break
		done
		common_var=$min_num
		return $min_num
	fi

	case "$opt" in
		false)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		true)
			for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep "$owner" | awk '{print $2}' -`; do
				min_num=$i
				break
			done
			;;
		*)
			p_echo "get_pid: wrong parameter"
			die "get_pid $ex_f $opt $owner"
			;;
	esac

	common_var=$min_num
	return $min_num
}

kill_pids()
{
	ex_f="$1"
	owner="$2"

	for i in `$ps_long | grep $ex_f | grep -v grep | grep -v httpsdctl | grep -v apachectl | grep $owner | awk '{print $2}' -`; do
		if [ $i -gt 1 ]; then
			$K_TERM $i >> $product_log 2>&1
		fi
	done
}

delete_user()
{
	local rm_user

	rm_user="$1"

	# if it is mailman user, remove its crontab from system
	if [ "X${rm_user}" = "X${mailman_user}" ]; then

		inten="remove crontab of ${rm_user}"
		echo "y" | $crontab -u "${mailman_user}" -r >> $product_log 2>&1 || die "$inten"

	fi

	inten="remove user $rm_user"
	echo_try "$inten"

	case "$machine" in
		BSD)
			echo "y" | pw userdel $rm_user>> $product_log 2>&1 && suc 
			pwd_mkdb /etc/master.passwd >> $product_log 2>&1
		;;
		linux|solaris)
			userdel  $rm_user>> $product_log 2>&1 && suc || die "$inten"
		;;
		Darwin)
			niutil -destroy / /users/"$rm_user" >> $product_log 2>&1 && suc || die "$inten"
			reload_darwin_netinfo
		;;
	esac
}

delete_group()
{
	local rm_group

	rm_group="$1"

	inten="remove group $rm_group"
	echo_try "$inten"

	case "$machine" in
		BSD)
			pw groupdel $rm_group>> $product_log 2>&1
			pwd_mkdb /etc/master.passwd >> $product_log 2>&1
		;;
		linux|solaris)
			mk_backup "/etc/group" cp f
			if [ -f "/etc/group" ]; then
				sed -e "/$rm_group/d" < /etc/group > /etc/group.tmp || die $inten
				mv -f /etc/group.tmp /etc/group  >> $product_log 2>&1
				if [ "$?" -ne 0 ]; then
					rsr_backup "/etc/group" cp f
					die $inten
				fi
			fi
		;;
		Darwin)
			niutil -destroy / /groups/"$rm_group" >> $product_log 2>&1 && suc || die "$inten"
			reload_darwin_netinfo
		;;
	esac
	suc
}

reload_darwin_netinfo()
{
    if [ -f /var/run/memberd.pid ]; then
	kill -HUP `cat /var/run/memberd.pid`
    else
	SystemStarter start memberd
    fi

    return 0
}

read_conf()
{
	[ -n "$prod_conf_t" ] || prod_conf_t=/etc/psa/psa.conf

	if [ -s $prod_conf_t ]; then
		tmp_var=`perl -e 'undef $/; $_=<>; s/#.*$//gm;
				s/^\s*(\S+)\s*/$1=/mg;
				print' $prod_conf_t`
		eval $tmp_var
	else
		if [ "X$do_upgrade" = "X1" ]; then
			[ 0$ignore_miss_conf -ne 1 ] && p_echo "Unable to find product configuration file: $prod_conf_t"
			return 1
		fi
	fi
	return 0
}

#-*- vim:syntax=sh

register_service(){

	[ -n "$1" ] || die "register_service: service name not specified"
	local inten="register service $1"
	echo_try "$inten"


# insserv for SuSE
	 /sbin/insserv -f "$1" >/dev/null 2>&1

	suc
}

#Need for register/unregister services into /etc/rc.conf for BSD OSes.
#Create or change strings such as service_option_variable="variable"
rc_service()
{
   local service="$1"
   local option="$2"
   local variable="$3"
   local comment="$4"
 
   local config="/etc/rc.conf"

   if [ "X$variable" = "Xdefault" ]; then
      remove_option_string "${service}_${option}" "$config"
      return 0
   fi

   if [ ! -f /etc/rc.conf ]; then
      die 'File /etc/rc.conf not found!'
   fi

   if [ "X$service" = "X" -o "X$option" = "X" -o "X$variable" = "X" ]; then
      die
   fi

   local flag="`grep "${service}_${option}" $config`"
   
   if [ "X$flag" = "X" ]; then
        if [ "X$comment" = "Xyes" ]; then
           echo "#Option for $service created by Plesk installer." >> $config
	fi
	echo "${service}_${option}=\"${variable}\"" >> $config || die 
   else
        sed -i "" -e 's|\('"${service}_${option}"'.*=\"\).*|\1'"${variable}"'\"|' $config  || die
   fi

   return 0
}

remove_option_string()
{
    #using: remove_option_string <option> <file>
    substring="$1"
    file="$2"

    awk '{
	if ($0 ~ "^'"$substring"'") {
	    next;
	}; 
	print $0; 
    }' < $file  > $file.tmp

    mv $file.tmp $file
}

selinux_close()
{
	if [ -z "$SELINUX_ENFORCE" -o "$SELINUX_ENFORCE" = "Disabled" ]; then
		return
	fi

	setenforce "$SELINUX_ENFORCE"
}

remove_modules()
{
	p_echo
	p_echo "===> Removing modules"

	local moduledir
	for moduledir in $PRODUCT_ROOT_D/var/modules/*; do
		if [ -d "$moduledir" -a -x "$moduledir/uninstall" ]; then
			local module=`basename $moduledist`
			echo_try "uninstall $module module"
			"$moduledir/uninstall" && suc || warn "uninstallation of $module module"
		fi
	done
}

#Invoke mysql
mysql()
{
	mysql_anydb -D$mysql_db_name "$@"
}

mysql_anydb()
{
	if test -z "$DB_IS_MYSQL41_COMPATIBLE"; then
		mysql41_init
	fi

	if [ "$DB_IS_MYSQL41_COMPATIBLE" != "compatible" -a "X$machine" != "XBSD" ]; then
		mysql41_exec_wrapper $mysql_client $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"
	else
		$mysql_client $mysql_user $mysql_passwd $mysql_args "$@" 2>>"$product_log"
	fi

	local status=$?
	if [ $status -gt 0 ]; then
		$mysql_client $mysql_user $mysql_passwd $mysql_args -D$mysql_db_name $mysql_args_raw -e "show innodb status" >>"$product_log" 2>&1
	fi
	return $status
}

# the function removes the "character set xxx" and "collate xxx" construction
# from -e * arguments, if there are any.
# otherwise, it removes the same things from standard input
mysql41_exec_wrapper()
{
	perl -e '$has_command = 0;
		$program = $ARGV[0];
		splice (@ARGV, 0, 1);
		sub remove_charsets($)
		{
			$refStr = shift;
			$$refStr =~ s/\b(medium|long|tiny)?text\s+character\s+set\s+binary(\s+collate\s+[\w]+)?\b/ $1blob /ig;
            $$refStr =~ s/\b(medium|long|tiny)?text\s+character\s+set\s+[\w]+\s+collate\s+[\w]+_bin\b/ $1blob /ig;
			$$refStr =~ s/(\bcharacter\s+set\s+binary(\s+collate\s+[\w]+)?\b)/ binary /ig;
			$$refStr =~ s/(\bcharacter\s+set\s+[\w]+\s+collate\s+[\w]+_bin\b)/ binary /ig;
			$$refStr =~ s/(\b(character\s+set|collate)\s+[\w]+\b)//ig;
		}
		foreach $n (0 .. $#ARGV) {
			if ($ARGV[$n] eq "-e") {
				$has_command = 1;
				remove_charsets \($ARGV[$n + 1]);
			}
		}
		if ($has_command) {
			exec $program, @ARGV or die "Cannot execute mysql";
		} else {
			open out_command, "|-", $program, @ARGV or die "Cannot start mysql";
			while (<STDIN>) {
				remove_charsets \($_);
				print out_command $_;
			}
			close out_command or die($! ? "Mysql returned an error: $!" : "Mysql exited with non-zero status $?");
		}' -- "$@"
}

# Invoke mysql in raw mode
mysql_raw()
{
	mysql $mysql_args_raw "$@"
}

mysql_raw_anydb()
{
	mysql_anydb $mysql_args_raw "$@"
}

mysql41_init()
{
	# not_installed is the default state
	# we must init it to avoid endless cycle
	DB_IS_MYSQL41_COMPATIBLE=not_installed
	if ! mysql_anydb </dev/null >>"$product_log" 2>&1; then
		return
	fi

	if db_test --any-db "SHOW VARIABLES LIKE 'version'" '$2 !~ /^(3|4\.0)\./'; then
		# if database is not yet initiailized, assume it compatible
		# otherwise, check the flag
		if
			db_test --any-db "SHOW DATABASES" '/^psa$/' 			&& db_test "SHOW TABLES" '/^misc$/' 			&& ! db_test "SELECT val FROM misc WHERE param = 'mysql41_compatible'" '/true/'
		then
			DB_IS_MYSQL41_COMPATIBLE='not_compatible'
		else
			DB_IS_MYSQL41_COMPATIBLE='compatible'
		fi
	fi
}

poppassd_super_server_config()
{
	local action="$1"

	case "$superserver" in
	    inetd)
		poppassd_rec="poppassd stream tcp nowait/1000 root /usr/sbin/tcpd $PRODUCT_ROOT_D/admin/sbin/poppassd"
		;;	
	    xinetd)
		poppassd_rec="service poppassd
{
socket_type             = stream
protocol                = tcp
port                    = 106
wait                    = no
disable                 = no
user                    = root
instances               = 1000
flags                   = KEEPALIVE
server                  = $PRODUCT_ROOT_D/admin/sbin/poppassd
}"
		;;
	    *)
		    die "Super server name unknown"
		;;
	esac

	super_server_action "$action" poppassd "$poppassd_rec"
}

## @@constructor set_qmail_params
qmail_super_server_config()
{
    local action="$1"
    local service="$2"

    case "$superserver" in
	inetd)
		qmail_inetd_templates
		;;
	xinetd)
		qmail_xinetd_templates
		;;
	*)
		die "Super server name unknown"
		;;
    esac

   	eval "template=\$${service}_rec"

    super_server_action "$action" "$service" "$template"
}

qmail_inetd_templates()
{
	maxconn=''
	if [ "$linux_distr" = "debian" ]; then 
	    maxconn='.1000'
	fi

	smtp_rec="smtp stream tcp nowait$maxconn root $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SMTPAUTH=1 END=1 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

	smtps_rec="smtps stream tcp nowait$maxconn root $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SMTPAUTH=1 END=1 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

	submission_rec="submission stream tcp nowait$maxconn qmaild $QMAIL_DIR/bin/tcp-env tcp-env /usr/bin/env SUBMISSION=1 SMTPAUTH=1 END=1 $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $QMAIL_DIR/bin/true $QMAIL_DIR/bin/cmd5checkpw $QMAIL_DIR/bin/true"

}

qmail_xinetd_templates()
{
    local TRUE_BIN
    TRUE_BIN=$QMAIL_DIR/bin/true
smtp_rec="service smtp
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	env             = SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

smtps_rec="service smtps
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = root
	instances       = UNLIMITED
	env             = SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/relaylock $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

submission_rec="service submission
{
	socket_type     = stream
	protocol        = tcp
	wait            = no
	disable		= no
	user            = qmaild
	instances       = UNLIMITED
	env             = SUBMISSION=1 SMTPAUTH=1
	server          = $QMAIL_DIR/bin/tcp-env
	server_args     = -Rt0 $QMAIL_DIR/bin/qmail-smtpd $QMAIL_DIR/bin/smtp_auth $TRUE_BIN $QMAIL_DIR/bin/cmd5checkpw $TRUE_BIN
}" 

}


rsr_backup()
{
	target="$1"
	dup="$2"
	opts="$3"
	common_var=0

#	if [ -$opts "$target" ]; then
		if [ -$opts "$target.$product_suff" ]; then
			case "$dup" in
				mv)
					mv -f  $target.$product_suff $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				cp)
					cp -fp  $target.$product_suff $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				*)
					p_echo " rsr_backup: wrong option -- must be 'cp' or 'mv'"
					;;
			esac
		else
			if [ -$opts "$target.$product_suffo" ]; then
			    case "$dup" in
				mv)
					mv -f  $target.$product_suffo $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				cp)
					cp -fp  $target.$product_suffo $target>> $product_log 2>&1
					common_var=1
					return 1
					;;
				*)
					p_echo " rsr_backup: wrong option -- must be 'cp' or 'mv'"
					;;
			    esac
			fi
		fi
#	else
#		case "$opts" in
#			f|d)
#				;;
#			*)
#				p_echo " rsr_backup: wrong option -- must be 'f' or 'd'"
#				;;
#		esac
#	fi
}

restore_named()
{
	cd "$PRODUCT_ROOT_D" >> $product_log 2>&1
	[ -f /etc/sysconfig/named ] && mv -f "/etc/sysconfig/named" "/etc/sysconfig/named.bak"
	rsr_backup "/etc/sysconfig/named" mv f

	[ -L $named_conf ] && rm -f "$named_conf"
	rsr_backup "$named_conf" mv f

	[ -L $rndc_conf ] && rm -f "$rndc_conf"
	rsr_backup "$rndc_conf" mv f

	case "$machine" in
		BSD*)
			rsr_backup /etc/named.boot mv f
			;;
		linux)
		    case "$linux_distr" in
			redhat)
			    chkconfig --add named >> $product_log 2>&1
#			    std_named_sh="/etc/rc.d/init.d/named"
#			    rsr_backup $std_named_sh mv f
#				if [ -f "$std_named_sh" ]; then
#					mv -f "$std_named_sh.${product}" "$std_named_sh"
#				fi
				;;
			slackware)
			    rsr_backup /etc/rc.d/rc.inet2 cp f
				;;
		    esac
			rsr_backup /etc/named.boot mv f
			;;
		solaris)
			rsr_backup /etc/named.boot mv f
			;;
	esac
}


restore_sendmail()
{
	[ -L $sendmail ] && rm -f "$sendmail"
	[ -L /usr/lib/sendmail ] && rm -f "/usr/lib/sendmail"

	rsr_backup "$sendmail" mv f

	case "$machine" in
		BSDI)
			rsr_backup /etc/sendmail.cf mv f
			;;
		*)
			;;
	esac

	if [ -f "$mail_local" ]; then
#		case "$machine" in
#			BSD)
#				chflags schg "$mail_local" >> $product_log 2>&1
#				;;
#			*)
#				;;
#		esac

		rsr_backup "$mail_local" mv f

		chmod 4555 "$mail_local" >> $product_log 2>&1
	fi
	case "$machine" in
		linux )
		    case "$linux_distr" in
			redhat)
			    chkconfig --add sendmail >> $product_log 2>&1
#			    rsr_backup "$sndml_ini" mv f
				;;
			slackware)
			     rsr_backup /etc/rc.d/rc.M mv f
				;;
		    esac
			;;
		solaris)
			rsr_backup "$sndml_ini" mv f
			;;
		*)
			;;
	esac

}

delete_startup_scripts()
{
	cd "$PRODUCT_ROOT_D" >> $product_log 2>&1

	case "$machine" in
		BSD)
			rm -f /usr/local/etc/rc.d/${product}.sh >> $product_log 2>&1
	#		rsr_backup /etc/rc.conf cp f

			rc_service "sendmail" "enable" "YES"
			rc_service "named" "enable" "YES"
			rc_service "mysqld" "enable" "NO"
			;;
		BSDI)
			if [ -f /etc/rc.local.${product} ]; then
				cp -p  /etc/rc.local.${product} /etc/rc.local >> $product_log 2>&1
			fi
			;;
		linux)
		    case "$linux_distr" in
			redhat)
			    chkconfig --del ${product}
			    rm -f /etc/rc.d/init.d/${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc0.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc1.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc2.d/K15${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc3.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc4.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc5.d/S77${product} >> $product_log 2>&1
#			    rm -f /etc/rc.d/rc6.d/K15${product} >> $product_log 2>&1
				;;
			slackware)
			    if [ -f /etc/rc.d/rc.local.${product} ]; then
				cp -p  /etc/rc.d/rc.local.${product} /etc/rc.d/rc.local >> $product_log 2>&1
			    fi
				;;
		    esac
		    ;;
		solaris)
			rm -f  /etc/init.d/${product} >> $product_log 2>&1
			if [ -f /etc/rc0.d/K01${product} ]; then
				rm -f /etc/rc0.d/K01${product} >> $product_log 2>&1
			fi

			if [ -f /etc/rc1.d/K01${product} ]; then
				rm -f /etc/rc1.d/K01${product} >> $product_log 2>&1
			fi

			if [ -f /etc/rc2.d/S77${product} ]; then
				rm -f /etc/rc2.d/S77${product} >> $product_log 2>&1
			fi
			;;
	esac
}

delete_crontab()
{

	$crontab -l 2>/dev/null > /tmp/crontab.${product}

	sed -e "s/^.*\/${product}\/admin\/sbin\/statistics.*//g" \
		-e "s/^.*\/${product}\/bin\/mysqldump.*//g" \
		-e "s/^.*\/usr\/sbin\/ntpdate.*//g" \
		< /tmp/crontab.${product} > /tmp/crontab.${product}_tmp

	mv -f /tmp/crontab.${product}_tmp /tmp/crontab.${product} >> $product_log 2>&1

	$crontab /tmp/crontab.${product}  >> $product_log 2>&1

	rm -f /tmp/crontab.${product} >> $product_log 2>&1

}

remove_ftpuser()
{
	user=$1
	ftpusers_file="/etc/ftpusers"

	egrep "^$user" $ftpusers_file >> /dev/null 2>&1

	case "$?" in
			0)
				sed -e "/$user/d" < $ftpusers_file > $ftpusers_file.tmp
				mv -f $ftpusers_file.tmp $ftpusers_file
				;;
			1)
				;;
			*)
				;;
	esac

}

remove_product_users_groups()
{

#	delete users of this(unsuccessful) installation
	for i in $users_created; do
		delete_user "$i"
	done
#	delete users with group=psacln (ftpusers and webusers)
	for i in `perl -e '$gid=getgrnam("'$clients_group'"); exit if (($gid eq "") || ($gid == 0)); while(($n,$u,$g) = (getpwent)[0,2,3]) {print "$n\n" if (($gid == $g) && ($u >= 500))}'`
	do
		delete_user "$i"
		remove_ftpuser "$i"
	done
#	delete users psaadm, psaftp
#	delete_user "$admin_user"  >> "$product_log" 2>&1
#	delete_user "$anonftp_user"  >> "$product_log" 2>&1

#	delete groups of this(unsuccessful) installation
	for i in $groups_created; do
		delete_group "$i"
	done
#	delete groups psaadm, psaftp, psacln
	delete_group "$admin_group"  >> "$product_log" 2>&1
	delete_group "$anonftp_group"  >> "$product_log" 2>&1
	delete_group "$clients_group"  >> "$product_log" 2>&1

}


undo_install()
{
	p_echo

	if pleskrc mysql status; then
		p_echo "===>Removing installed $PRODUCT_NAME components ... "
		remove_modules
		pleskrc mysql stop

		mysql_pid_file=$mysql_bddir/*.pid
		if [ -f "$mysql_pid_file" ]; then
			rm -f "$mysql_pid_file"
		fi
	fi

	$START_SH stop >> "$product_log" 2>&1

	proftpd_super_server_config remove

	super_server_action remove pop3
	super_server_action remove pop-3
	super_server_action remove imap4
	super_server_action remove imap2
	super_server_action remove imap
	qmail_super_server_config remove smtp
	qmail_super_server_config remove smtps
	qmail_super_server_config remove submission
	poppassd_super_server_config remove

	remove_product_users_groups

	if [ -f "/etc/ftpchroot" ]; then
	    sed -e "s/^@$clients_group//g" < /etc/ftpchroot > /etc/ftpchroot.tmp
	    mv -f /etc/ftpchroot.tmp /etc/ftpchroot  >> $product_log 2>&1
	fi

	if [ -f /etc/shells ]; then
	    case "$machine" in
		BSD|BSDI)
		    sed -e "s/[/]*sbin[/]*nologin//" < /etc/shells > /etc/shells.tmp
		;;
		linux|solaris)
		    sed -e "s/[/]*bin[/]*false//" < /etc/shells > /etc/shells.tmp
		;;
	    esac
	    mv -f /etc/shells.tmp /etc/shells  >> $product_log 2>&1
	fi

	remove_tmp_state

	restore_named
	restore_sendmail
	delete_startup_scripts
	delete_crontab

	cd /usr/local  >> $product_log 2>&1

	suc
}

smart_undo_install()
{
	[ "X$trigger_uninstall" = "X1" -o "X$do_patch" = "X1" -o "X$do_reconfigure" = "X1" ] && return
	[ "X$PLESK_INSTALLER_NOUNDO" != "X" ] && return
	# trigger_uninstall - trigger what smart_undo_install is already working now(recurrence)
	trigger_uninstall=1

	if [ "X$can_uninstall" = "X1" ]; then
		if [ "X$do_upgrade" = "X1" ]; then
			undo_upgrade
		else
		    if [ "X$machine" != "XBSD" ]; then
			undo_install
		    fi
		fi
	fi

	# put suggestions for user what to do
	call_optional_function failure_note
}
undo_upgrade()
{
	p_echo   "    The attempt to upgrade $prev_product_full"
	p_echo   "    from version $prev_version to $product_full $product_version has failed."

	if [ -f "$product_sav_tar" ]; then
	
		p_echo 

		p_echo "    Now restore contents of $PRODUCT_NAME from $product_sav_tar"
		p_echo 
		get_pid $PRODUCT_ROOT_D/mysql/bin/safe_mysqld true root
		req_pid=$common_var
		if [ $req_pid -gt 1 ]; then
			$K_KILL $req_pid >> $product_log 2>&1 
			sleep 2
			mysql_pid_file=$mysql_bddir/*.pid
			kill_pids $PRODUCT_ROOT_D/mysql/libexec/mysqld mysql
			sleep 2
			if [ -f "$mysql_pid_file" ]; then
				rm -f $mysql_pid_file
			fi
		fi

		$START_SH stop >> $product_log 2>&1
		sleep 2

		rm -Rf $PRODUCT_ROOT_D
		qmail_super_server_config remove "smtp"
		qmail_super_server_config remove "smtps"
		proftpd_super_server_config remove
		poppassd_super_server_config remove
		

		cd /
        	tar xvf $product_sav_tar > /dev/null 2>&1
		case "$?" in
			0)
#				rm -f $product_sav_tar 		
			;;
			*)
				p_echo 
				p_echo 
				p_echo "ERROR: restoration of files from $product_sav_tar has failed."
				p_echo "       Please restore them manually."
				p_echo 
				p_echo "Exiting..."
				p_echo 
				exit 0
			;;
		esac
	fi
	
}

export LANG="C"

prog="`basename $0`"
action="$1"
service="$2"
cmds_num="$#"

usage()
{
	echo "Usage: $prog [--enable|--disable] <service>"
	echo ""
	echo "SERVICES:"
	echo "            panel   Applying patches for sw-cp-server."
	echo "            apache  Applying patches for apache server."
	echo "            courier Applying patches for courier-imap."
	echo "            all     Applying patches for all services described above."

	exit 1
}

[ "$cmds_num" -eq 2 ] || usage

services_list="panel apache courier"

read_conf

product_log="compliance.log"

apache_ssl_conf="$HTTPD_CONF_D/ssl-global.conf"
sw_server_ssl_conf="$PRODUCT_ROOT_D/admin/conf/cipher.lst"
courier_conf="/etc/courier-imap/imapd-ssl /etc/courier-imap/pop3d-ssl"

# common things
#------------------------------------------------------------------
check_services()
{
	local service="$1"
	local flag

	[ "$service" = "all" ] && return 0

	for entry in $services_list; do
		if [ "$1" = "$entry" ]; then
			flag=1
			break
		fi
	done

	[ -z "$flag" ] && return 1

	return 0
}

fail()
{
	p_echo "failed"
}

do_enable()
{
	local service="$1"
	local key="$2"
	local value="$3"
	local config="$4"
	local bkp_file="$5"

	echo_try "enable PCI compliance fixes for $service"

	[ -z "$bkp_file" ] && bkp_file="${config}.pci"

	# checking on already modified file and config file exists
	if [ -e "$bkp_file" ]; then
		echo -n "already modified... "
		suc
		return 2
	fi

	if [ ! -e "$config" ]; then
		echo -n "file: $config not found... "
		fail
		return 1
	fi

	# Comment default strings for RedHat based distros
	if [ "$service" = "apache service" ]; then
		cat "$config" | awk '{
			if (/^<VirtualHost _default_/) {
				flag=1;
			}
			if (/^<\/VirtualHost/) {
				flag=0;
			}
			if (flag && (/^SSLProtocol/ || /^SSLCipherSuite/)) {
				printf ("# ");
				print;
				next;
			}
			print;
		}' > ${config}.new
		mv -f ${config}.new $config
	fi

	# Get original record and backup
	original_str="`cat $config | grep -- \"$key\" |grep -v \"^#\"`"
	echo "$original_str" > $bkp_file

	# Replace record to new value
	if [ -z "$original_str" ]; then
		# Hack for apache
		val="`cat $config | grep -- \"<IfModule mod_ssl.c>\" |grep -v \"^#\"`"
		if [ -z "$val" ]; then
			echo "$value" >> ${config}
		else
			sed -e "s|<IfModule mod_ssl.c>|<IfModule mod_ssl.c>\n$value|" \
			    < $config > ${config}.new &&  mv -f ${config}.new $config
		fi
	else
		sed -e "s|^$original_str$|$value|" < $config > ${config}.new && \
		mv -f ${config}.new $config
	fi

	suc
	return 0
}

do_disable()
{
	local service="$1"
	local key="$2"
	local value="$3" # for compat with 'enable' action
	local config="$4"
	local bkp_file="$5"

	echo_try "disable PCI compliance fixes for $service"

	[ -z "$bkp_file" ] && bkp_file="${config}.pci"

	# checking on already modified file and config file exists
	if [ ! -e "$bkp_file" ]; then
		echo -n "already original config... "
		suc
		return 2
	fi

	if [ ! -e "$config" ]; then
		echo -n "file: $config not found... "
		fail
		return 1
	fi

	# Get record from config and original record
	value="`cat $config | grep -- \"$key\" |grep -v \"^#\"`"
	original_str="`cat $bkp_file`"

	# Replace record to new value
	sed -e "s|^$value$|$original_str|" < $config > ${config}.new && \
	mv -f ${config}.new $config && \
	rm -f $bkp_file

	suc
	return 0
}

service_restart()
{
	local serv="$1"
	local status="$2"

	if [ "$status" -eq 0 ]; then 
		echo_try "restart $serv"
		pleskrc $serv restart >/dev/null && suc || fail
	fi

	return $?
}

#-----------------------------------------------------------------------------
# service specific routines
#-----------------------------------------------------------------------------

# panel routines
#-----------------------------------------------------------------------------
panel_status()
{
	return 0
}

panel_action()
{
	local action="$1"
	local key=".*"
	local value="ADH-AES256-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:ADH-AES128-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:KRB5-DES-CBC3-MD5:KRB5-DES-CBC3-SHA:ADH-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DES-CBC3-MD5:DHE-DSS-RC4-SHA:KRB5-RC4-MD5:KRB5-RC4-SHA:ADH-RC4-MD5:RC4-SHA:RC4-MD5:RC2-CBC-MD5:RC4-MD5"

	touch $sw_server_ssl_conf

	flag=0
	do_$action "panel" "$key" "$value" "$sw_server_ssl_conf" || flag=1

	is_empty="`cat $sw_server_ssl_conf | sed '/^$/d'`"
	[ -z "$is_empty" ] && rm -f "$sw_server_ssl_conf"

	panel_service="sw-cp-server"
	service_restart panel "$flag"

	return $flag
}

courier_action()
{
	local action="$1"
	local key='TLS_CIPHER_LIST'
	local value='TLS_CIPHER_LIST="HIGH:MEDIUM:!SSLv2:!LOW:!EXP:!aNULL:@STRENGTH"'

	flag=0
	for conffile in $courier_conf; do
		do_$action "courier-imap service" "$key" "$value" "$conffile" || flag=1
	done

	set_courier_imap_params
	service_restart courier "$flag"

	return $flag
}

apache_action()
{
	local action="$1"
	local key1='SSLProtocol'
	local key2='SSLCipherSuite'
	local val1='SSLProtocol -ALL +SSLv3 +TLSv1'
	local val2='SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM'

	flag=0
	do_$action "apache service" "$key1" "$val1" "$apache_ssl_conf" "$HTTPD_CONF_D/ssl_conf.pci.1" || flag=1
	do_$action "apache service" "$key2" "$val2" "$apache_ssl_conf" "$HTTPD_CONF_D/ssl_conf.pci.2" || flag=1

	set_apache_params
	service_restart apache "$flag"

	return $flag
}

all_action()
{
    local action="$1"

    for entry in $services_list; do
	    service="$entry"
	    ${entry}_action $action
	    echo ""
    done

    return 0
}

# getopt like selector
#-----------------------------------------------------------------------------
case "$action" in
	--enable)
		check_services $service || echo "Unsupported service: $service"
		${service}_action enable
		exit $?
		break
		;;

	--disable)
		check_services $service || echo "Unsupported service: $service"
		${service}_action disable
		exit $?
		break
		;;
	*)
		usage
		;;
esac
