#!/bin/sh
# mediawiki v1.3.3  (c) 6.12.2010 by Andreas Ley  (u) 6.3.2026
# Install mediawiki instance

# Mediawiki requires GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
# ALTER and DROP are required for schema updates upon upgrading mediawiki software

PATH="/bin:/usr/bin"
export PATH

usage()
{
	echo "Usage: `basename $0` [-q] [-f] [-p] [-e extension] url [...]" >&2
	#echo "-v  verbose mode" >&2
	echo "-q  quiet mode" >&2
	echo "-f  force database update even though symlinks suggest it should already have been done" >&2
	echo "-p  print only path" >&2
	ls -1 /var/lib/mediawiki/extensions | xargs | sed 's/ /, /g;s/^/-e  enable extension (option can be given multiple times) (possible values: /;s/$/)/' | lbreak
	exit 1
}

set -- `getopt hxvqfpe: $*` || usage

trace=false
verbose=true
force=false
print_path=false
while :; do
	case $1 in
		-h)	sed '1d;s/^# *//;/^$/q' $0; usage;;
		-x)	set -x; trace=true; shift;;
		-v)	verbose=true; unset quiet; shift;;
		-q)	verbose=false; quiet="--quiet"; shift;;
		-f)	force=true; shift;;
		-p)	print_path=true; shift;;
		-e)	extensions="${extensions} $2"; shift 2;;
		--)	shift; break;;
	esac
done

test $# -lt 1 && usage

if test ! -d /var/lib/mediawiki/mw-config; then
	echo "Requires installed mediawiki package." >&2
	exit 1
fi

umask 022

configure()
{
	host "${host}" >/dev/null && productive=true || productive=false
	host "test-${host}" >/dev/null && test=true || test=false

	! ${test} || ${productive} && echo "https://${host}${path}/mw-config/"
	${test} && echo "https://test-${host}${path}/mw-config/"
	echo
	echo "Download the offered LocalSettings.php, save it to ${wiki}/LocalSettings.php, e.g. with:" | lbreak
	! ${test} || ${productive} && echo "scp -p LocalSettings.php $LOGNAME@${host}:${wiki}/LocalSettings.php"
	${test} && echo "scp -p LocalSettings.php $LOGNAME@test-${host}:${wiki}/LocalSettings.php"
	echo "and call this script again!" | lbreak
}

for url do
	url="`echo \"${url}\" | sed 's!^[^:/]*://!!;s!/*$!!'`"
	case "${url}" in
		*/*)	host="`echo \"${url}\" | cut -d/ -f1`"
			path="/`echo \"${url}\" | cut -d/ -f2-`"
			;;
		*)	host="${url}"
			path=
			;;
	esac

	conf="/etc/apache2/sites-enabled/000-default.conf"
	if test ! -s "${conf}"; then
		defines="/var/www/${host}/conf/httpd.conf"
		conf="/var/www/${host}/conf/vhost.conf"
	fi

	case "${path}" in
		/~*)	wiki=`echo "${path}" | perl -ne 'print +(getpwnam($1))[7],"/public_html",$2,"\n" if (/^\/~([^\/]+)(\/.*)/);'`;;
		*)	wiki="`awk 'BEGIN{IGNORECASE=1}$1==\"DocumentRoot\"{sub(\"^\\\"\",\"\",$2);sub(\"\\\"\$\",\"\",$2);print$2}' \"${conf}\"`${path}"
			while echo "${wiki}" | egrep -q '\${[^}]+}'; do
				var="$(echo "${wiki}" | sed -E 's/^.*\$\{([^}]+)\}.*$/\1/')"
				# FIXME: This does not handle double-quoted values
				val="$(sed -E -n "s/^Define[[:space:]]+${var}[[:space:]]+(.*)\$/\\1/p" "${defines}")"
				wiki="$(echo "${wiki}" | sed "s!\${${var}}!${val}!g")"
			done;;
	esac

	if ${print_path}; then
		echo "${wiki}"
		continue
	fi

	# If the web based configuration has been activated, and there are
	# extensions to install:
	# Enable extensions in local configuration
	if test -s "${wiki}/LocalSettings.php" -a -n "${extensions}"; then
		for extension in ${extensions}; do
			if test -s "/var/lib/mediawiki/extensions/${extension}/extension.json"; then
				if ! grep "wfLoadExtension([[:space:]]*'${extension}'[[:space:]]*);" "${wiki}/LocalSettings.php" >/dev/null; then
					${verbose} && echo
					${verbose} && echo "Enabling ${extension} extension"
					echo "wfLoadExtension('${extension}');" >>"${wiki}/LocalSettings.php"
				fi
			else
				echo "Invalid extension: ${extension}"
			fi
		done
	fi


	# Phase 1: No wiki is found - install it
	if test ! -d "${wiki}/extensions"; then
		${verbose} && echo
		${verbose} && echo "Installing mediawiki to ${wiki}" | lbreak
		cd /var/lib/mediawiki || exit 1
		mkdir -p "${wiki}/extensions"
		cp -r --preserve=mode,timestamps mw-config/ "${wiki}"
		chmod go-w "${wiki}/mw-config"
		fgrep -ls '/includes/WebStart.php' *.php | while read file; do
			(echo "<?php"
			echo "putenv( 'MW_INSTALL_PATH=' . __DIR__ );"
			echo "require '/var/lib/mediawiki/${file}';") >"${wiki}/${file}"
		done
		find . \( -path ./cache -o -path ./config -o -path ./extensions -o -path ./images \) -prune -o -type l ! -lname '/etc/mediawiki/*' -print | \
			cpio --quiet -pdm "${wiki}" 2>/dev/null

		${verbose} && echo
		${verbose} && echo "Now configure the new mediawiki using e.g.:"
		${verbose} && configure

	# If the web based configuration has been activated, and there still is
	# a config directory, the web based configuration is no longer needed:
	# Phase 2: Remove configuration scripts
	elif test -s "${wiki}/LocalSettings.php" -a -d "${wiki}/mw-config"; then
		${verbose} && echo
		${verbose} && echo "Removing mediawiki configuration scripts"
		rm -rf "${wiki}/mw-config"

	# Phase 3: If the wiki is already installed and there is no config directory, check wether an upgrade is required
	elif ${force} || test -h "${wiki}/serialized"; then
		# Upgrade an existing old mediawiki
		${verbose} && echo
		${verbose} && echo "Upgrading Mediawiki and databases" | lbreak

		cd /var/lib/mediawiki || exit 1
		fgrep -ls '/includes/WebStart.php' *.php | while read file; do
			rm -f "${wiki}/${file}"
			(echo "<?php"
			echo "putenv( 'MW_INSTALL_PATH=' . __DIR__ );"
			echo "require '/var/lib/mediawiki/${file}';") >"${wiki}/${file}"
		done
		# At least composer.json would be missing
		find . \( -path ./cache -o -path ./config -o -path ./extensions -o -path ./images -o -path ./mw-config \) -prune -o -type l ! -lname '/etc/mediawiki/*' -print | \
			cpio --quiet -pdm "${wiki}" 2>/dev/null

		# Upgrade databases
		${verbose} && echo
		# update.php tries to defer wiki location from ".."
		# which fails due to "maintenance" being a symlink
		env MW_INSTALL_PATH="${wiki}" php "${wiki}/maintenance/update.php" ${quiet} --quick

		rm -f "${wiki}/serialized" "${wiki}/profileinfo.php"
	else
		${verbose} && echo
		${verbose} && echo "Mediawiki already installed to ${wiki}" | lbreak
		if test -d "${wiki}/mw-config"; then
			${verbose} && echo
			${verbose} && echo "Configure mediawiki using e.g.:"
			${verbose} && configure
		fi
	fi
	${verbose} && echo
done

exit 0
