#!/bin/bash

set -e
umask 002

if [ $# -lt 5 ]; then
	echo "Usage: $0 [client] [domain] [host] [extra_basedir] [relative/path/to/script.php] [php_params]"
	echo "Example: $0 client domain.com www : /scripts/cron.php daily"
	exit 3
fi

sn=${0##*/}
VER=${sn##phpcron}
v_major=${VER:0:1}
v_minor=${VER:1}

CHRDIR=/chroot/httpd${VER}
CHRBIN=/usr/sbin/chroot

case $VER in
	52)
		CHRDIR_ALT=/chroot/httpd-old
		;;
	53)
		CHRDIR_ALT=/chroot/httpd
		;;
	*)
		CHRDIR_ALT=/chroot/NONEXISTENT
		;;
esac

if ! [ -d "$CHRDIR" ]; then
	if [ -n "$CHRDIR_ALT" -a -d "$CHRDIR_ALT" ]; then
		CHRDIR=$CHRDIR_ALT
	else
	    echo "The chroot $CHRDIR doesn't exist."
		exit 8
	fi
fi

PHPINI=/etc/php/${v_major}.${v_minor}/cli/php.ini
PHPINI_ALT=/etc/php${v_major}/cli/php.ini

if ! [ -f "$CHRDIR$PHPINI" ]; then
	if ! [ -f "$CHRDIR$PHPINI_ALT" ]; then
		echo "$CHRDIR$PHPINI doesn't exist."
		echo "$CHRDIR$PHPINI_ALT doesn't exist."
		exit 8
	else
		PHPINI=$PHPINI_ALT
	fi
fi

VH_CLI=$1
shift
VH_DOM=$1
shift
VH_HOST=$1
shift
X_OBD=$1
shift
PHP_SCRIPT=$1
shift

if [ $# -gt 0 ]; then
	PHP_ARGV="-- $@"
else
	PHP_ARGV=""
fi

CLIENTDIR="/web/${VH_CLI}"
VHDIR="/web/${VH_CLI}/${VH_DOM}/${VH_HOST}"
VHTMP="/web/temp/${VH_DOM}/${VH_HOST}"
PHP_FP="${VHDIR}/${PHP_SCRIPT}"

# check dirs

if ! [ -d "$VHDIR" ]; then
	echo "ERROR: vhost dir doesn't exist ($VHDIR)"
	exit 9
fi

if ! [ -d "$VHTMP" ]; then
	echo "ERROR: temp dir doesn't exist ($VHTMP)"
	exit 10
fi

if ! [ -f "${PHP_FP}" ]; then
	echo "ERROR: PHP script doesn't exist ($PHP_FP)"
	exit 11
fi

# assemble php directives

PHPC=""
PHPC="$PHPC -d open_basedir='${VHTMP}:${VHDIR}:${X_OBD}'"
PHPC="$PHPC -d realpath_cache_basedir='${VHTMP}:${VHDIR}:${X_OBD}'"
PHPC="$PHPC -d realpath_turbo.open_basedir='${VHTMP}:${VHDIR}:${X_OBD}'"
PHPC="$PHPC -d sendmail_path='/usr/bin/smtp-wrapper ${VH_DOM}'"
if [ -d "${VHTMP}/tmp" ]; then
	PHPC="$PHPC -d sys_temp_dir='${VHTMP}/tmp'"
else
	PHPC="$PHPC -d sys_temp_dir='${VHTMP}'"
fi

# run script

$CHRBIN $CHRDIR su www-data -s /bin/sh -c "cd ${VHTMP} && /usr/bin/php -c ${PHPINI} ${PHPC} -f '${PHP_FP}' ${PHP_ARGV}"
