#!/bin/bash

set -e
umask 002

sn=${0##*/}
VER=${sn##phprun}
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

CURDIR=`pwd`

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

if ! [ -d $CHRDIR$CURDIR ]; then
    echo "This dir $CURDIR doesn't exist in chroot."
	exit 9
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

if [ $# -gt 0 ]; then
	PHPFILE=$1
	shift
	PHPARGV=$@
	$CHRBIN $CHRDIR su www-data -s /bin/sh -c "cd / && cd $CURDIR && /usr/bin/php -c $PHPINI -f '$PHPFILE' -- $PHPARGV"
else
	echo "Usage: $0 [php_script_name] [parameters]"
fi
