#!/bin/sh
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
#

#
# Plesk script
#


### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
# Migration manager tables will be managed by plesk


# echo message to product log, unless debug
p_echo()
{
    if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then
        echo "$@"
    else
        echo "$@" >> "$product_log" 2>&1
    fi
}

# echo message to product log without new line, unless debug
pnnl_echo()
{
    if [ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" -o -z "$product_log" ] ; then
        echo -n "$*"
    else
        echo -n "$*" >> "$product_log" 2>&1
    fi
}

die()
{
	PACKAGE_SCRIPT_FAILED="$*"

	printf "\a\a"
	report_problem \
		"ERROR while trying to $*" \
		"Check the error reason(see log file: ${product_log}), fix and try again"

	selinux_close

	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()
{
	[ -n "$product_problems_log" ] || product_problems_log="/dev/stderr"

	p_echo
	if [ "0$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

	product_log_tail | send_error_report_with_input "Problem: $@"

	[ -n "$PLESK_INSTALLER_DEBUG" -o -n "$PLESK_INSTALLER_VERBOSE" ] || \
		product_log_tail

	problems_occured=1
}

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

# do not call it w/o input! Use send_error_report in these cases.
send_error_report_with_input()
{
	{
		echo $@
		echo ""
		if [ -n "$error_report_context" ]; then
			echo "Context: $error_report_context"
			echo ""
		fi
		cat -
	} | $PRODUCT_ROOT_D/admin/bin/send-error-report "install" >/dev/null 2>&1
}

detect_vz()
{
	PLESK_VZ=0
	PLESK_VE_HW_NODE=0
	PLESK_VZ_TYPE=

	local issue_file="/etc/issue"
	local vzcheck_file="/proc/self/status"
	[ -f "$vzcheck_file" ] || return 1

	local env_id=`sed -ne 's|^envID\:[[:space:]]*\([[:digit:]]\+\)$|\1|p' "$vzcheck_file"`
	[ -n "$env_id" ] || return 1
	if [ "$env_id" = "0" ]; then
		# Either VZ/OpenVZ HW node or unjailed CloudLinux
		PLESK_VE_HW_NODE=1
		return 1
	fi

	if grep -q "CloudLinux" "$issue_file" >/dev/null 2>&1 ; then
		return 1
	fi

	if [ -f "/proc/vz/veredir" ]; then
		PLESK_VZ_TYPE="vz"
	elif [ -d "/proc/vz" ]; then
		PLESK_VZ_TYPE="openvz"
	fi

	PLESK_VZ=1
	return 0
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
label_file_once()
{
	local _fname _mess _messLines _fileHead _tmpFile

	test $# -eq 2 || die 'label_file_once() not enough arguments'
	
	_fname="${1}"
	_mess="${2}"

	inten="add header to file ${_fname}"
	echo_try $inten

	if [ ! -f "${_fname}" ]; then
		p_echo "can not add header to file ${_fname} : file does not exist"
		return
	fi
	_messLines=`printf "${_mess}" | wc -l | awk '{print $NF}'`

	_tmpFile=`basename "${_fname}"`
	_tmpFile=`mktemp "/tmp/${_tmpFile}.XXXXXX"` || die "can not create temporary file"
	head -n ${_messLines} "${_fname}" > "${_tmpFile}"

	printf "${_mess}" | diff -q - "${_tmpFile}" 1>/dev/null
	if [ $? -eq 0 ]; then
		p_echo "file ${_fname} already contains required header"
		rm -f "${_tmpFile}"
		return
	fi
	rm -f "${_tmpFile}"

	# preserve permissions, not optimal, need to rework
	cp -p "${_fname}" "${_fname}.tmp"

	printf "${_mess}" | cat - "${_fname}" > "${_fname}.tmp"
	cp -f "${_fname}.tmp" "${_fname}"
	rm -f "${_fname}.tmp"
	p_echo "completed successfully"
}

product_log_tail()
{
	[ -f "$product_log" ] || return 0
	tac "$product_log" | awk '/^START/ { exit } { print }' | tac
}

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
}

# setup new value for parameter
# $1 config file name $2 paramater name, $3 parameter value
conf_setval()
{
	cat $1 | awk -v varname="$2" -v varvalue="$3" 'BEGIN { f = 0 }
{ if ($1 == varname) { f = 1; print varname "\t" varvalue } else { print $0 } }
END { if (f == 0) { print "\n" varname "\t" varvalue } }' 		> $1.new

	if [ -s "$1.new" ]; then
	  if cmp -s $1.new $1; then
  		rm -f $1.new
		return 1
	  else
		rm -f $1.old
		ln $1  $1.old
		mv -f $1.new $1
		rm -f $1.old
		chmod 644 "$1"
		return 0
	  fi
	fi
	return 2
}

conf_setvar()
{
	conf_setval "$@"
}

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

	setenforce "$SELINUX_ENFORCE"
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

#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"
	K_TEST="/bin/kill -0"

	users_created=""
	groups_created=""

	certificate_file="$PRODUCT_ETC_D/httpsd.pem"
	services="/etc/services"
	mtab="/etc/mtab"
	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/libexec/postfix"
	PRODUCT_BOOTSTRAPPER_DIR="/usr/local/psa/bootstrapper/pp11.5.30-bootstrapper"
	AUTOGENERATED_CONFIGS="#ATTENTION!\n#\n#DO NOT MODIFY THIS FILE BECAUSE IT WAS GENERATED AUTOMATICALLY,\n#SO ALL YOUR CHANGES WILL BE LOST THE NEXT TIME THE FILE IS GENERATED.\n"
	AUTOGENERATED_CONFIGS_UPGRADE="#ATTENTION!\n#\n#DO NOT MODIFY THIS FILE BECAUSE IT WAS GENERATED AUTOMATICALLY,\n#SO ALL YOUR CHANGES WILL BE LOST AFTER YOU UPGRADE PARALLELS PLESK PANEL.\n"

	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"
		useradd_options="-r"
	    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
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
#-*- vim:syntax=sh

export LANG=C LC_MESSAGES=C LC_ALL=C
umask 022

[ -z "$PLESK_INSTALLER_DEBUG" ] || set -x
[ -z "$PLESK_INSTALLER_STRICT_MODE" ] || set -e

action="$1"
product_log="/tmp/plesk-whc-installation.log"
product_problems_log="/tmp/plesk-whc-problems.log"
problems_occured=0


awstats_common()
{
	set_common_params
	read_conf

	[  -n "/usr/share/awstats/tools" -a -d "/usr/share/awstats/tools" ] && conf_setvar ${prod_conf_t} AWSTATS_TOOLS_D "/usr/share/awstats/tools" || true
	[ -n "/usr/share/awstats/wwwroot/cgi-bin"  -a -f "/usr/share/awstats/wwwroot/cgi-bin/awstats.pl" ] && conf_setvar ${prod_conf_t} AWSTATS_BIN_D "/usr/share/awstats/wwwroot/cgi-bin" || true

###	On SuSE awstats.model.conf is awstats.conf or awstats.conf.web, so make symlink

	[ -e "/etc/awstats/awstats.conf" -a ! -e "/etc/awstats/awstats.model.conf" ] && ln -s /etc/awstats/awstats.conf /etc/awstats/awstats.model.conf
	[ -e "/etc/awstats/awstats.conf.web" -a ! -e "/etc/awstats/awstats.model.conf" ] && ln -s /etc/awstats/awstats.conf.web /etc/awstats/awstats.model.conf

	find /etc/awstats/ /usr/local/psa/etc/awstats/ -type f -name 'awstats.*' 2>/dev/null | 	xargs perl -pi -e 's|^DirIcons=.*|DirIcons="/awstats-icon"|g'
}

awstats_remove_crontask()
{
    awstats_cron=/etc/cron.d/awstats
    if [ -f $awstats_cron ]; then
        tmp=`mktemp ${awstats_cron}.XXXXXX`
        sed -e 's/^[^#].*$/# \0/' ${awstats_cron} > $tmp
        mv $tmp $awstats_cron
    fi
}

configure()
{
	awstats_common
	awstats_remove_crontask
	label_file_once "$AWSTATS_ETC_D/awstats.model.conf" "${AUTOGENERATED_CONFIGS}"
}

upgrade_configuration()
{
    :
}

deconfigure()
{
    :
}

detach()
{
    :
}

status()
{
    :
}

case $action in
    configure) configure ;;
    attach) attach ;;
    deconfigure) deconfigure ;;
    detach) detach ;;
    upgrade_configuration) upgrade_configuration ;;
    status) status ;;
    *) echo "Unknown action '$1'"; exit 1;;
esac
