export MAJORVER="${PKGVER%%.*}"
abinfo "PostgreSQL major release: $MAJORVER"
if ! [[ "$MAJORVER" =~ ^[0-9]+$ ]] ; then
	abdie "Unexpected major version $MAJORVER."
fi

# Check if PKGDEP actually contains the release we want to point to.
if [ "${PKGDEP/postgresql-$MAJORVER/}" == "$PKGVER" ] ; then
	abdie "PKGDEP isn't updated - Check the defines file."
fi

abinfo "Creating directories ..."
mkdir -pv "$PKGDIR"/usr/{bin,lib/pkgconfig}

abinfo "Deploying pkg-config symlinks ..."
for pc in \
	$(find /usr/lib/postgresql-"$MAJORVER"/lib/pkgconfig \
		-maxdepth 1 -type f -name '*.pc' -printf "%P\n")
	do
	ln -sv ../postgresql-"$MAJORVER"/lib/pkgconfig/"$pc" \
		"$PKGDIR"/usr/lib/pkgconfig/"$pc"
done

abinfo "Deploying executable symlinks ..."
for bin in \
	$(find /usr/lib/postgresql-${MAJORVER}/bin -type f -executable -printf '%P\n')
	do
	ln -sv ../lib/postgresql-"$MAJORVER"/bin/"$bin" \
		"$PKGDIR"/usr/bin/"$bin"
done

abinfo "Deploying manual page symlinks ..."
for man in $(find /usr/share/postgresql-"$MAJORVER"/man -mindepth 1 -type f -printf '%P\n'); do
	dir="$(dirname $man)"
	if [ ! -d "$PKGDIR"/usr/share/man/"$dir" ] ; then
		mkdir -pv "$PKGDIR"/usr/share/man/"$dir"
	fi
	# For now PostgreSQL manual pages does not have translations.
	# If anytime they have, then we must handle them, since they are
	# one directory deeper than normal manual pages.
	# Calculate how deep is the manual page file relative to man/.
	depth=${dir//[^\/]/}
	depth=$(( ${#depth} + 1 ))
	# Get the relative path to man/.
	rel=$(eval "printf '../%.0s' {1..$depth}")
	rel=${rel%\/}
	ln -sv "$rel"/../postgresql-"$MAJORVER"/man/"$man" \
		"$PKGDIR"/usr/share/man/"$man"
done

abinfo "Deploying postinst ..."
sed -e "s|@MAJORVER@|${MAJORVER}|g" \
	"$SRCDIR"/autobuild/preinst.1.in \
	> "$SRCDIR"/autobuild/preinst.1

# NOTE Files are not deployed during preinst, so the translations will NOT be available.
# This is a dumb way to "integrate" translation files into the script.
abinfo "Deploying translations ..."
echo "LINGUAS=(${GETTEXT_LINGUAS[@]})" > "$SRCDIR"/autobuild/TRANSLATIONS
for lang in "${GETTEXT_LINGUAS[@]}" ; do
	msgfmt -vo "$SRCDIR"/autobuild/po/"$lang".mo \
		"$SRCDIR"/autobuild/po/"$lang".po
	echo "TRANSLATION_${lang}=\"" >> "$SRCDIR"/autobuild/TRANSLATIONS
	base64 "$SRCDIR"/autobuild/po/"$lang".mo >> "$SRCDIR"/autobuild/TRANSLATIONS
	echo '"' >> "$SRCDIR"/autobuild/TRANSLATIONS
done
cat "$SRCDIR"/autobuild/preinst.1 "$SRCDIR"/autobuild/TRANSLATIONS "$SRCDIR"/autobuild/preinst.2 > \
	"$SRCDIR"/autobuild/preinst
