#!/bin/sh -e

# trailing slash is important here
dest="docs/"

cd $WORKDIR

nonfatal() { echo "** $*" >&2; exit 0; }

indexdir="/usr/share/doc/indexhtml"
indexfile="$indexdir/index.html"

[ -s "$indexfile" ] || nonfatal "$indexfile not found"

[ -n "$GLOBAL_LOCALE" ] ||
	echo "** warning: GLOBAL_LOCALE empty, fallback to en_US (use/l10n?)">&2

LANG="${GLOBAL_LOCALE:-en_US}" indexhtml-update

# delete brocken symlinks before cp -L
find "$indexdir" -xtype l 2>/dev/null -exec rm {} \;
# copy with conversion of symlinks to directories and files
cp -aL "$indexdir" "$dest"

# delete links with absolute PATH
sed -i -e '/file:\/\/\//d' -e '/href="\//d' "$dest"/index*.html

mkredir() {
	cat >"${1}index.html" <<-EOF
	<html>
	<head>
	<meta http-equiv="refresh" content="0;url=${2}index.html">
	<title>Redirecting...</title>
	</head>
	<body>
	<h1>Redirecting...</h1>
	</body>
	</html>
	EOF
}

mkredir "" "$dest"	# /index.html -> docs/index.html

docdir="/usr/share/doc/documentation"
for docdir in ${GLOBAL_DOCS:-}; do
	docdir=/usr/share/doc/"$docdir"
	### no need to replace symlinks with hardlinks by now? (-aH)
	if [ -d "$docdir" ]; then
		cp -aH "$docdir" "$dest"
	else
		echo "** $docdir not found" >&2
	fi
done
