#!/bin/sh

. $(dirname $0)/common.sh

check_cwd

if [ -z "$LANGS" ]; then
    LANGS=[a-z][a-z]-[A-Z][A-Z]
fi

for lang in $LANGS; do
    mkdir -p public/$lang
    publish_dir=$(get_publish_directory "$lang" "html")
    tempfile=$(mktemp build-log-$lang-XXXXXX)
    echo "Building HTML version for lang=$lang"
    if ./bin/build-html --lang=$lang >$tempfile 2>&1; then
	mv $publish_dir/debian-handbook/* public/$lang/
	echo "SUCCESS."
    else
	echo "ERROR: Build failed. Last 200 lines of the build log:"
	tail -n 200 $tempfile
    fi
    mv $tempfile public/$lang/build-log.txt
done

# Some cleanups to save space
rm -f public/*/images/chap-*.png # Chapter pictures only used in PDF
rm -f public/*/images/cover.png  # Cover picture (only used in PDF/ePub)
rm -f public/*/images/*.dia      # Sources of diagrams

jdupes --recurse --linksoft --paramorder public/en-US $(ls -d public/*-*|grep -v en-US)

cat >public/index.html <<EOF
<html>
<body>
<h1>Automated builds of the Debian Administrator's Handbook</h1>
<p>The following languages are auto-built out of the $CI_COMMIT_REF_NAME
branch. At the time of the build, the branch was pointing
to commit $CI_COMMIT_SHA.</p>
<ul>
EOF
for dir in public/*-*; do
    lang=$(basename $dir)
    echo "<li><a href='$lang'>$lang</a></li>" >>public/index.html
done
cat >>public/index.html <<EOF
</ul>
</body>
</html>
EOF
