#! /bin/sh -efu

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

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

PATH="/usr/sbin:$PATH"

moodledir='/var/www/webapps/moodle'
configfilename='config.php'
configfile="$moodledir/$configfilename"
suffix=

. shell-error

TEMP=`getopt -n "$PROG" -o c:,f:,s: -l config:,file:,suffix: -- "$@"`
eval set -- "$TEMP"

while :; do
	case "$1" in
		--)
			shift
			break
			;;
		-c|-f|--config|--file)
			shift
			configfile="$1"
			;;
		-s|--suffix)
			shift
			suffix="$1"
			;;
		*) fatal "Unrecognized option: $1"
			;;
	esac
	shift
done

[ -e "$configfile" ] || fatal "No search configfile $configfile!"

[ -L "$configfile" ] && {
	message "$configfile is symlink!"
	exit
}

printf "%s\n" "$configfile" \
	| sed -rn 's@^[[:space:]]*([^[:space:]]*/)?([^/[:space:]]+)[[:space:]]*$@\2\t\1@p' \
	| {
	read -r configfilename configfiledir

	if [ -z "$suffix" ]; then
		suffix=`mt-getconfigsuffix ${configfile:=--file="$configfile"}`
	fi
	newconfigfilename="$configfilename.$suffix"

	if [ -z "$configfiledir" ]; then
		configfiledir="./"
	fi

	pushd "$configfiledir"
	mv "$configfilename" "$newconfigfilename"
	ln -sf "$newconfigfilename" "$configfilename"
	popd
}
