#!/usr/bin/env bash
#
# Copyright 2008, Centova Technologies Inc.
#
# If suPHP or other PHP privilege separation mechanisms are installed (or 
# removed) after Centova Cast is installed, Centova Cast's web interface will
# stop working due to communication problems between the web interface and
# the back-end.
#
# Use this script to update Centova Cast's configuration to match your new
# PHP configuration.
#
# DO NOT USE THIS SCRIPT UNLESS YOU KNOW WHAT YOU'RE DOING.  Enabling privsep
# mode will reduce Centova Cast's performance.
#
# Usage:
#   ./set-privsep.sh on		- use this if suPHP is now ENABLED
#   ./set-privsep.sh off	- use this if suPHP is now DISABLED
#

[ $# -lt 1 ] && echo "Usage: $0 <on|off>" && exit 1

SYSPATH=`dirname $0`/../system
RUNASCC="$SYSPATH/runascc/runascc"

if [ "$1" == "on" ]; then
	PRIVSEP=1
elif [ "$1" == "off" ]; then
	PRIVSEP=0
else
	echo "Sorry, this script does not speak gibberish.  Specify either 'on' or 'off'."
	exit 1
fi

CONFIGPHP="$SYSPATH/config.php"
[ ! -f $CONFIGPHP ] && echo "Configuration file $CONFIGPHP does not exist" && exit 1

SANE=`$RUNASCC exec ccmanage sanitycheck nopassword | grep -c '^OK '`
[ $SANE -eq 0 ] && echo "Sanity check failed -- Centova Cast does not appear to be functional" && exit 1

USERUNASCC="false"
USEDAEMON="false"

[ $PRIVSEP -eq 0 ] && USERUNASCC="true"
[ $PRIVSEP -gt 0 ] && USEDAEMON="true"

# backup
cp $SYSPATH/config.php $SYSPATH/config.php.pre-privsep

# make sure daemon conf directives exist
HASDAEMONCONF=`cat $SYSPATH/config.php.pre-privsep | grep -c 'USE_DAEMON'`
if [ $HASDAEMONCONF -eq 0 ]; then
	cat $SYSPATH/config.php.pre-privsep \
		| sed "s/\?>/define('USE_DAEMON',false);\ndefine('DAEMON_HOST','127.0.0.1');\ndefine('DAEMON_PORT',2199);\n?>/g" \
		> $SYSPATH/config.php.tmp
	mv -f $SYSPATH/config.php.tmp $SYSPATH/config.php.pre-privsep
fi

# update config
cat $SYSPATH/config.php.pre-privsep \
    | sed "s/define('USE_RUNASCC',.*/define('USE_RUNASCC',${USERUNASCC});/g" \
    | sed "s/define('USE_DAEMON',.*/define('USE_DAEMON',${USEDAEMON});/g" \
	> $SYSPATH/config.php	

# kill any running castd process
$SYSPATH/../scripts/castdctl.sh stop >/dev/null

# start castd if needed
if [ $PRIVSEP -gt 0 ]; then
	$SYSPATH/../scripts/castdctl.sh start >/dev/null
	[ $? -gt 0 ] && echo "Could not start cast daemon" && exit 1
fi

# check for success
YIPPIE=`$RUNASCC exec ccmanage sanitycheck nopassword | grep -c '^OK '`
if [ $YIPPIE -gt 0 ]; then
	echo "Privilege separation configuration updated successfully"
else
	echo "Privilege separation configuration update failed:"
	$RUNASCC exec ccmanage sanitycheck nopassword
fi

