#!/usr/bin/env bash
#
# Script to build the Landing Page using
# The Tor Projects's i18n and lego projects in a Debian-based system.
#

# Parameters
DIRNAME="`dirname $0`"
BASEPATH="$DIRNAME/../"
OUTPUT_PATH="public"
BUILD="lektor build --output-path $OUTPUT_PATH"
PROJECT_FILE="onion-launchpad.lektorproject"

# Setup the environment
source $DIRNAME/env

# Backup the project file
cp $PROJECT_FILE $PROJECT_FILE.backup

# Pre-build script
$DIRNAME/pre-build

# Build
# The build command might fail in the first time, so we run it again if needed
echo "Building..."
for n in 1 2 3; do
  echo "Starting build $n..."
  $BUILD

  if [ "$?" != "0" ]; then
    # Restore the project file
    mv $PROJECT_FILE.backup $PROJECT_FILE

    exit 1
  fi
done

# Restore the project file
mv $PROJECT_FILE.backup $PROJECT_FILE

# Ensure that all subpages for the default language exists
#
# This is not created by default but might be handy.
# Needs an update in each page's base href so all relative links continue to work.
find content -name contents.lr | sed -e 's/^content//' -e 's/contents.lr//' | while read path; do
  mkdir -p "$OUTPUT_PATH/$LEKTOR_DEFAULT_LANGUAGE/$path"
  cp "$OUTPUT_PATH/$path/index.html" "$OUTPUT_PATH/$LEKTOR_DEFAULT_LANGUAGE/$path"
  sed -i -e 's|<head>|<head>\n    <base href="../">|' "$OUTPUT_PATH/$LEKTOR_DEFAULT_LANGUAGE/$path/index.html"
done
