#! /bin/sh -efu

#
# Moodle tools
#
# @package   mt
# @copyright 2012 Aleksey Avdeev <solo@altlinux.ru>
# @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
#

PROG="${0##*/}"

moodledir='/var/www/webapps/moodle'
configfilename='config.php'
configfile="$moodledir/$configfilename"
msg=
regquote="['\\\"]"

. shell-error

TEMP=`getopt -n "$PROG" -o f:,m: -l file:,msg:,no-quote -- "$@"`
eval set -- "$TEMP"

while :; do
	case "$1" in
		--)
			shift
			break
			;;
		-f|--file)
			shift
			configfile="$1"
			;;
		-m|--msg)
			shift
			msg="$1"
			;;
		--no-quote)
			regquote=
			;;
		*) fatal "Unrecognized option: $1"
			;;
	esac
	shift
done

name="$1"
var="$2"

if [ -n "$msg" ]; then
	msg="\\t\\/\\/ $msg"
fi

var="`echo "$var" | sed -r "s@([][/(){}\\^\\$\\"'&?])@\\\\\\\\\\\\1@g"`"

sed -ri "
/[[:space:]]*<\\?php([[:space:]].*)\$/,/\\?>/{
	/^[[:space:]]*\\\$CFG->$name[[:space:]]*=[[:space:]]*($regquote)[^'\"]*\\1[[:space:]]*;/{
		s/^([[:space:]]*\\\$CFG->$name[[:space:]]*=[[:space:]]*($regquote))([^'\"]*)((\\2[[:space:]]*;).*)$/\\/\\/ \\1\\3\\4\\n\\1$var\\5$msg/
	}
}
" "$configfile"
