#!/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

### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

# echo message to product log and console (always visible)
pp_echo()
{
    if [ -n "$product_log" ] ; then
        echo "$@" >> "$product_log" 2>&1
    fi
    echo "$@"
}

# 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
}

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.
get_userID()
{
# try to get UID
	common_var=`id -u "$1" 2>/dev/null` 

# if id returns 0 the all is ok
	test "$?" -eq "0" -a -n "$common_var"
}
### Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
# vim:ft=sh

initial_conf()
{
	DEMO_VERSION="no"
	PRODNAME="psa"
	PRODUCT_NAME="psa"
	product_full="Plesk"
	product=${PRODNAME}
	PRODUCT_FULL_NAME="Plesk"

	product_etc="/etc/${PRODNAME}"
	prod_conf_t="/etc/psa/psa.conf"
	prodkey="$product_etc/$PRODNAME.key"

	minimal_changes=""

	EXTERNAL_PACKAGES=""
	EXTERNAL_PACKAGES_DIR=""

	BUILDER_UID="10007"

	PERL5LIB=/usr/local/psa/lib/perl5/site_perl/5.8.8:/usr/local/psa/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi
	export PERL5LIB

        support_contact="http://www.parallels.com/support"
	sales_email="sales@parallels.com"

	product_version="11.5.30"
	product_db_version="011005030"
	conceived_os_vendor=CentOS
	conceived_os_version="5"
	osrels="centos5"

	prev_product="plesk"
	prev_clients_group="${prev_product}cln"

        clients_group="${product}cln"
        clients_GID=10001

        services_group="psaserv"
        services_GID=10003

        product_suff="saved_by_${product}".`date "+%m.%d;%H:%M"`
        product_suffo="saved_by_${product}"

	PREV_PRODUCT_ROOT_D="/usr/local/${prev_product}"

	# plesk default password
	if [ "X$DEMO_VERSION" = "Xyes" ]; then
		PRODUCT_DEFAULT_PASSWORD="plesk"
	else
		PRODUCT_DEFAULT_PASSWORD="setup"
	fi
}

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
}

 #default values

product_default_conf()
{

PRODUCT_ROOT_D=/usr/local/psa
PRODUCT_RC_D=/etc/init.d
PRODUCT_ETC_D=/usr/local/psa/etc
PLESK_LIBEXEC_DIR=/usr/lib64/plesk-9.0
HTTPD_VHOSTS_D=/var/www/vhosts
HTTPD_CONF_D=/etc/httpd/conf
HTTPD_INCLUDE_D=/etc/httpd/conf.d
HTTPD_BIN=/usr/sbin/httpd
HTTPD_LOG_D=/var/log/httpd
HTTPD_SERVICE=httpd
QMAIL_ROOT_D=/var/qmail
PLESK_MAILNAMES_D=/var/qmail/mailnames
RBLSMTPD=/usr/sbin/rblsmtpd
FTPD_CONF=/etc/proftpd.conf
FTPD_CONF_INC=/etc/proftpd.include
FTPD_BIN_D=/usr/bin
FTPD_VAR_D=/var/run/proftpd
FTPD_SCOREBOARD=/var/run/proftpd/scoreboard
NAMED_RUN_ROOT_D=/var/named/run-root
NAMED_OPTIONS_CONF=
NAMED_ZONES_CONF=
WEB_STAT=/usr/bin/webalizer
MYSQL_VAR_D=/var/lib/mysql
MYSQL_BIN_D=/usr/bin
MYSQL_SOCKET=/var/lib/mysql/mysql.sock
PGSQL_DATA_D=/var/lib/pgsql/data
PGSQL_CONF_D=/var/lib/pgsql/data
PGSQL_BIN_D=/usr/bin
DUMP_D=/var/lib/psa/dumps
DUMP_TMP_D=/tmp
MAILMAN_ROOT_D=/usr/lib/mailman
MAILMAN_VAR_D=/var/lib/mailman
PYTHON_BIN=/usr/bin/python2.6
CATALINA_HOME=/usr/share/tomcat5
DRWEB_ROOT_D=/opt/drweb
DRWEB_ETC_D=/etc/drweb
GPG_BIN=/usr/bin/gpg
TAR_BIN=/bin/tar
AWSTATS_ETC_D=/etc/awstats
AWSTATS_BIN_D=/var/www/cgi-bin/awstats
AWSTATS_TOOLS_D=/usr/share/awstats
AWSTATS_DOC_D=/var/www/html/awstats
OPENSSL_BIN=/usr/bin/openssl
LIB_SSL_PATH=/lib/libssl.so
LIB_CRYPTO_PATH=/lib/libcrypto.so
CLIENT_PHP_BIN=/usr/local/psa/bin/php-cli
SNI_SUPPORT=false
APS_DB_DRIVER_LIBRARY=/usr/lib64/libmysqlserver.so.2
IPv6_DISABLED=false
SA_MAX_MAIL_SIZE=256000

}
### 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/lib64/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-2013. Parallels IP Holdings GmbH. All Rights Reserved.

# vim:ft=sh:

prog="`basename $0`"

usage() {
cat << EOT
	Usage: $prog --domain-name domain --sys-user-login user [--webspace-name webspace] [--verbose]

		--domain-name		domain		upgrade specified domain. Mandatory.
		--sys-user-login	login		FTP system user login for specified domain. Mandatory.
		--webspace-name		webspace	Webspace name, if specified domain is addon (optional)
		--verbose						Be more verbose
EOT
	exit 1
}

while [ "$#" -gt 0 ]; do
	case "$1" in
		--domain-name)
			if [ "$#" -ge 2 ]; then
				domain="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--sys-user-login)
			if [ "$#" -ge 2 ]; then
				user="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--webspace-name)
			if [ "$#" -ge 2 ]; then
				webspace="$2"
				shift 2
			else
				echo "Not enough arguments" >&2
				echo >&2
				usage
			fi
			;;
		--verbose)
			verbose=1
			shift
			;;
		-h|--help)
			usage
			;;
		*)
			echo "Unknown argument '$1'"
			echo
			usage
		;;
	esac
done

if [ -z "$domain" -o -z "$user" ]; then
	echo "Either --sys-user-login or --domain-name not specified" >&2
	echo  >&2
	usage
fi

info()
{
	if [ -n "$verbose" -o -n "$PLESK_INSTALLER_VERBOSE" -o -n "$PLESK_INSTALLER_DEBUG" ]; then
		echo $@
	fi
}

remove_stale_symlink_if_exists()
{
	local domain=$1
	local entry=$2

	if [ -z "$domain" -o -z "$entry" ]; then
		echo "remove_stale_symlink: either domain or entry not specified" >&2
		return 1
	fi

	local path="./$domain/$entry"
	if [ -L "$path" -a ! -e "$path" ]; then
		info "Removing broken symlink to $entry directory"
		unlink "$path" || rc=1
	fi
}

update_vhost()
{
	rc=0
	local domain="$1"
	local user="$2"
	local webspace="$3"

	if ! get_userID "$user"; then
		echo "User '$user' does not exist" >&2
		exit 1
	fi

	if [ ! -d "./system" ]; then
		info "Creating system directory"
		if ! mkdir ./system; then
			echo "Cannot create 'system' folder" >&2
			return 1
		fi
	fi

	# Main domain directory should have 0710 sysuser:psaserv
	if [ -d "./$domain" ]; then
		chown "$user:psaserv" "./$domain" || rc=1
		chmod 0710 "./$domain" || rc=1
		remove_stale_symlink_if_exists "$domain" ".plesk"
		remove_stale_symlink_if_exists "$domain" "logs"
	elif [ -z "$webspace" ]; then
		# if [ ! -d "./$domain" ] then this is likely a sub-domain on upgrade from Plesk 9 
		# (in which case ./system/$domain/logs/ was already created by CU during upgrade)
		# or already upgraded addon or sub-domain
		echo "Domain '$domain' directory does not exist and it is not an addon or sub-domain"
		exit 1
	fi

	# Create system area
	if [ ! -e "./system/$domain" ]; then
		info "Creating system/$domain directory"
		if ! mkdir "./system/$domain"; then
			echo "Cannot create ./system/$domain" >&2
			return 1
		fi
		chown root:psaserv ./system/$domain || rc=1
		chmod 0711 ./system/$domain || rc=1
	fi

	# pd/ should be in system area
	if [ ! -e "./system/$domain/pd" -a -e "./$domain/pd" ]; then
		info "Relocating pd directory with password files for protected directories"
		mv -f "./$domain/pd" "./system/$domain/pd" || rc=1
		chmod 0710 "./system/$domain/pd" || rc=1
		find  -P ./system/$domain/pd/ -maxdepth 1 -type f \
			-execdir chown root:psaserv {} \+ \
			-execdir chmod 0640 {} \+
	elif [ ! -e "./system/$domain/pd" -a -e "./$domain/.plesk/pd" ]; then
		info "Relocating pd directory with password files for protected directories (11.5.21)"
		mv -f "./$domain/.plesk/pd" "./system/$domain/pd" || rc=1
	elif [ ! -e "./system/$domain/pd" -a -e "./system/$domain/.plesk/pd" ]; then
		info "Relocating pd directory with password files for protected directories (11.5.22)"
		mv -f "./system/$domain/.plesk/pd" "./system/$domain/pd" || rc=1
	fi

	# logs/ should be in system area and have 0700 psaadm:root
	if [ -z "$webspace" -a -d "./$domain/logs" -a ! -L "./$domain/logs" -a -z "`find \"./$domain/logs\" -type f 2>/dev/null`" -a -n "`find \"./$domain/logs\" -mindepth 1 -type d 2>/dev/null`" ]; then
		# Workaround upgrade issue from Plesk 9.x due to subdomains upgrade (creates new domains) before running this script
		# The condition above assumes that no additional files are created by relink-vhost-logs utility (such as README)!
		rm -rf "./$domain/logs"
	fi

	if [ ! -e "./system/$domain/logs" -a ! -L "./system/$domain/logs" -a -d "./$domain/logs" ]; then
		info "Relocating logs directory (<< 11.5.22)"
		mv -f "./$domain/logs" "./system/$domain/logs" || rc=1
	fi

	if [ ! -e "./system/$domain/logs" -a ! -L "./system/$domain/logs" -a -d "./$domain/statistics/logs" -a ! -L "./$domain/statistics/logs" ]; then
		info "Relocating logs directory"
		mv -f "./$domain/statistics/logs" "./system/$domain/logs" || rc=1
	fi

	if [ -d "./system/$domain/logs" -a ! -L "./system/$domain/logs" ]; then
		chown psaadm:root ./system/$domain/logs
		chmod 0700 ./system/$domain/logs
	fi

	# statistics/ should be in system area
	local had_statistics="yes"; [ -e "./$domain/statistics" ] || had_statistics=

	if [ ! -e "./system/$domain/statistics" -a -e "./$domain/statistics" ]; then
		info "Relocating statistics directory"
		mv -f "./$domain/statistics" "./system/$domain/statistics" || rc=1
	elif [ ! -e "./system/$domain/statistics" -a -e "./$domain/.plesk/statistics" ]; then
		info "Relocating statistics directory (11.5.21)"
		mv -f "./$domain/.plesk/statistics" "./system/$domain/statistics" || rc=1
	elif [ ! -e "./system/$domain/statistics" -a -e "./system/$domain/.plesk/statistics" ]; then
		info "Relocating statistics directory (11.5.22)"
		mv -f "./system/$domain/.plesk/statistics" "./system/$domain/statistics" || rc=1
	fi

	# conf/ should be in system area
	local had_conf="yes"; [ -e "./$domain/conf" ] || had_conf=

	if [ ! -e "./system/$domain/conf" -a -e "./$domain/conf" ]; then
		info "Relocating conf directory"
		mv -f "./$domain/conf" "./system/$domain/conf" || rc=1
	elif [ ! -e "./system/$domain/conf" -a -e "./$domain/.plesk/conf" ]; then
		info "Relocating conf directory (11.5.21)"
		mv -f "./$domain/.plesk/conf" "./system/$domain/conf" || rc=1
	elif [ ! -e "./system/$domain/conf" -a -e "./system/$domain/.plesk/conf" ]; then
		info "Relocating conf directory (11.5.22)"
		mv -f "./system/$domain/.plesk/conf" "./system/$domain/conf" || rc=1
	fi

	# Compatibility symlinks to conf/ and statistics/ to support customized Apache configuration and other crazy stuff
	if [ -n "$had_conf" -a \( ! -e "./$domain/conf" -o -L "./$domain/conf" \) ]; then
		info "Creating compat symlink for $domain/conf"
		ln -snf "../system/$domain/conf" "./$domain/conf" || rc=1
	fi

	if [ -n "$had_statistics" -a \( ! -e "./$domain/statistics" -o -L "./$domain/statistics" \) ]; then
		info "Creating compat symlink for $domain/statistics"
		ln -snf "../system/$domain/statistics" "./$domain/statistics" || rc=1
	fi

	# etc/php.ini should be in system area
	if [ ! -e "./system/$domain/etc/php.ini" -a -f "./$domain/etc/php.ini" ]; then
		info "Relocating etc/php.ini file"
		mkdir "./system/$domain/etc"
		chown root:0 "./system/$domain/etc/"
		mv -f "./$domain/etc/php.ini" "./system/$domain/etc/php.ini" || rc=1
		rmdir "./$domain/etc" >/dev/null 2>&1
	fi

	# logs/ should be hardlinked from system area if this is a webspace (main domain)
	if [ -z "$webspace" -a \( ! -e "./$domain/logs" -o -L "./$domain/logs" \) -a -d "./system/$domain/logs" ]; then
		info "Hardlink logs from system area"
		unlink "./$domain/logs" >/dev/null 2>&1
		$PRODUCT_ROOT_D/admin/sbin/relink-vhost-logs --create --domain-name "$domain" --sys-user-login "$user" || rc=1
	fi

	# There should be convenience symlink statistics/logs in system area
	if [ ! -e "./system/$domain/statistics/logs" -o -L "./system/$domain/statistics/logs" ]; then
		info "Symlink statistics/logs for backward compatibility"
		ln -snf "../logs" "./system/$domain/statistics/logs"
	fi

	if [ -z "$webspace" ]; then
		# Atempt to remove .plesk for webspace if upgrade from 20, 21
		rmdir "./system/$domain/.plesk" "./$domain/.plesk" >/dev/null 2>&1
	fi

	[ -n "$webspace" ] || return $rc

	if [ ! -d "$webspace" ]; then
		pp_echo "Webspace '$webspace' directory does not exist"
		return 1
	fi

	if [ ! -d "./system/$webspace" ]; then
		pp_echo "Webspace '$webspace' system directory does not exist"
		return 1
	fi

	# Remove possible leftover symlinks
	unlink "./$domain/logs" >/dev/null 2>&1
	unlink "./system/$domain/logs" >/dev/null 2>&1

	# logs/ of addon or sub-domain should be in system area and have 0700 psaadm:root
	if [ ! -e "./system/$domain/logs" -a -d "./$webspace/logs/$domain" ]; then
		info "Relocating addon domain logs directory (11.5.21)"
		mv -f "./$webspace/logs/$domain" "./system/$domain/logs" || rc=1
		chown psaadm:root ./system/$domain/logs
		chmod 0700 ./system/$domain/logs

	elif [ ! -e "./system/$domain/logs" -a -e "./system/$webspace/logs/$domain" -a ! -L "./system/$webspace/logs/$domain" ]; then
		info "Relocating addon domain logs directory (11.5.22)"
		mv -f "./system/$webspace/logs/$domain" "./system/$domain/logs" || rc=1
	fi

	# logs/ of addon or sub-domain should be hardlinked from system area to ./domain.tld/logs/child-domain.tld/
	if [ \( ! -e "./$webspace/logs/$domain" -o -L "./$webspace/logs/$domain" \) -a -d "./system/$domain/logs" ]; then
		info "Hardlink logs from system area of addon domain into webspace"
		unlink "./system/$webspace/logs/$domain" >/dev/null 2>&1 # remove symlink created in previews before 11.5.29
		unlink "./$webspace/logs/$domain" >/dev/null 2>&1 # if logs/ is not a symlink already, but logs/$domain is
		$PRODUCT_ROOT_D/admin/sbin/relink-vhost-logs --create --domain-name "$domain" --sys-user-login "$user" --webspace-name "$webspace" || rc=1
	fi

	# Remove possible leftover empty .plesk directory and links
	unlink "./$domain/.plesk" >/dev/null 2>&1
	unlink "./system/$domain/.plesk" >/dev/null 2>&1
	rmdir "./system/$domain/.plesk" "./system/$webspace/.plesk/$domain" "./$webspace/.plesk/$domain" "./system/$webspace/.plesk" "./$webspace/.plesk" >/dev/null 2>&1

	return $rc
}

product_default_conf
initial_conf
set_common_params
read_conf
umask 022

cd $HTTPD_VHOSTS_D

if [ -n "$webspace" ]; then
	info "Performing update of webspace $webspace first"
 	if ! update_vhost $webspace $user; then
		pp_echo "Failed to update parent webspace $webspace for domain $domain"
		exit 1
	fi
fi

if ! update_vhost $domain $user $webspace; then
	pp_echo "Failed to update domain $domain"
	exit 1
else
	pp_echo "Upgrade of domain $domain completed successfully"
fi
