#!/bin/sh
# migrate_gre v1.0  (c) 12.9.2021 by Andreas Ley  (u) 13.8.2025
# List vhost calls for all non-GRE migrated servers

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

usage()
{
	#echo "Usage: ${0##*/} [-G] [filter]" >&2
	echo "Usage: ${0##*/} [filter]" >&2
	echo "-v  verbose mode" >&2
	#echo "-G  Transition phase: add -G to vhost calls" >&2
	exit 1
}

trace=false
verbose=false
opt_G=
#while getopts hxvG OPTION; do
while getopts hxv OPTION; do
	case ${OPTION} in
		h)	sed '1d;s/^# *//;/^$/q' "$0" >&2; usage;;
		x)	set -x; trace=true;;
		v)	verbose=true;;
		#G)	opt_G=' -G';;
		?)	usage;;
	esac
done
_XPG=1 shift $((${OPTIND} - 1))
test $# -gt 1 && usage

tmpname="$(/bin/mktemp)"
trap "rm -f \"${tmpname}\"" 0 1 2 3 15

set -e

cd /var/www

if test $# -eq 0; then
	ls -1
else
	ls -1 | grep "$1"
fi | grep -v stage | while read fqdn; do
	#if test -f "${fqdn}/conf/httpd.conf" && grep -q '2a00:1398:9:fd10' "${fqdn}/conf/httpd.conf"; then
	if test -f "${fqdn}/conf/httpd.conf"; then
		${verbose} && echo "### ${fqdn} ###"

		# Easiest way. Should check owner of DocumentRoot
		user="$(stat -c %U "${fqdn}/run")"
		opt="-u ${user}"

		if echo "${fqdn}" | grep -q '^[^.]*www'; then
			stage="$(echo "${fqdn}" | sed 's/^\([^.]*\)www/\1stage/')"
		else
			stage="stage-${fqdn}"
		fi
		test -f "${stage}/conf/httpd.conf" && opt="${opt} -r"

		case "${fqdn}" in
			www.*)	domain="${fqdn##www.}"; opt_A=' -A';;
			*)	domain=; opt_A=;;
		esac
		if test -s "${fqdn}/conf/aliases"; then
			for alias in $(sed 's/[[:space:]][[:space:]]*#.*//;/^#/d;/^[[:space:]]*$/d' "${fqdn}/conf/aliases"); do
				if test -n "${domain}" -a "${alias}" = "${domain}"; then
					opt_A=
				else
					opt="${opt} -a ${alias}"
				fi
			done
		fi
		opt="${opt}${opt_A}"

		if test -s "${fqdn}/conf/identity.conf"; then
			addr="$(sed -n 's/^[[:space:]]*ServerAdmin[[:space:]][[:space:]]*//p' "${fqdn}/conf/identity.conf" | head -1)"
			if test -n "${addr}" -a "${addr}" != "webmaster@${domain}"; then
				opt="${opt} -m ${addr}"
			fi
		fi

		if test -s "${fqdn}/conf/modules"; then
			for module in $(sed 's/[[:space:]][[:space:]]*#.*//;/^#/d;/^[[:space:]]*$/d' "${fqdn}/conf/modules"); do
				opt="${opt} -M ${module}"
			done
		fi

		echo "vhost -v${opt_G} ${opt} ${fqdn}"
	fi
done

exit 0
