#!/bin/sh

# $FreeBSD: head/misc/qtchooser/files/update-qtchooser-wrapper.in 531601 2020-04-13 12:35:58Z tcberner $

# If a port installs Qt version-specific binaries (e.g. "designer" which existed as a Qt4 application
# and exists as a Qt5 application and will probably be a Qt6 application) which should have a
# qtchooser-based wrapper, the port should set `QT_BINARIES=yes`.
#
# When QT_BINARIES is set to yes, compatibility symlinks (designer -> qtchooser, so that
# qtchooser can run designer-qt5 or whatever is the selected Qt version) are installed by the port.

PREFIX=/usr/local
BINDIR=${PREFIX}/bin
QTCHOOSER=${BINDIR}/qtchooser
VERSIONS=5

if [ ! -d ${BINDIR} ] ; then
	echo "Binary directory '${BINDIR}' missing." >&2
	exit 1
fi

if [ ! -x ${QTCHOOSER} ] ; then
	echo "Qtchooser binary '${QTCHOOSER}' missing." >&2
	exit 2
fi

remove_links() {
	for file in $(find -L ${BINDIR} -maxdepth 1 -samefile ${QTCHOOSER}) ; do
		if [ ! -L ${file} ] ; then
			continue
		fi
		# If at least one versioned executable is found for this name, keep the
		# qtchooser compatibility symlink for this name; otherwise, remove it.
		local found=0
		for version in ${VERSIONS} ; do
			version_bin_dir=${PREFIX}/lib/qt${version}/bin
			target=${version_bin_dir}/$(basename ${file})
			if [ -x ${target} ] ; then
				found=1
				break
			fi
		done
		if [ ${found} -eq 0 ] ; then
			rm ${file}
		fi
	done
}

create_links() {
	for version in ${VERSIONS} ; do
		version_bin_dir=${PREFIX}/lib/qt${version}/bin
		if [ -d ${version_bin_dir} ] ; then
			for file in $(find ${version_bin_dir} -type f -maxdepth 1) ; do
				target=${BINDIR}/$(basename ${file})
				if [ ! -L ${target} -a ! -f ${target} ] ; then
					ln -s ${QTCHOOSER} ${target}
				fi
			done
		fi
	done
}

remove_links
create_links
