#!/usr/bin/env bash
#
# Build the Landing Page using GitLab Runner.
# Makes the compiled page available at the ./public folder.
#
# This has been deprecated by GitLab:
# https://gitlab.com/gitlab-org/gitlab/-/issues/385235
#

# Parameters
DIRNAME="`dirname $0`"
BASEPATH="$DIRNAME/../"

# Check for an existing GitLab Runner installation
if ! which gitlab-runner &> /dev/null; then
  echo "Please install gitlab-runner first"
  exit 1
fi

# Get GitLab Runner version
GR_VERSION="`gitlab-runner --version | grep "^Version:" | cut -d ':' -f 2 | sed -e 's/ //g'`"
GR_MAJOR_VERSION="`echo $GR_VERSION | cut -d '.' -f 1`"

# Check for GitLab Runner version
if (( $GR_MAJOR_VERSION >= 16 )); then
  echo "You're running GitLab Runner version $GR_VERSION."
  echo "Since version 16.0, running standalone jobs is no longer supported :("
  echo "For details, check https://gitlab.com/gitlab-org/gitlab/-/issues/385235"
  exit 1
fi

# Ensure we're in the root repository folder
cd "$BASEPATH" &> /dev/null

# Do this hack while the following feature is not available at the installed
# GitLab Runner: https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3246
cp .gitlab-ci-deployment.yml .gitlab-ci.yml

# Ensure that the public folder exists
mkdir -p public

# Code to copy the artifact back to the working copy thanks to
# https://gitlab.com/gitlab-org/gitlab-runner/-/issues/2226#note_396408902
gitlab-runner exec docker build \
  --docker-volumes $(pwd)/public:/public \
  --post-build-script "rm -rf /public/* && cp -R public/* /public && chown -R $(id -u):$(id -g) /public"

# Store the build exit status
STATUS="$?"

# Restore the main CI/CD config file
git restore .gitlab-ci.yml

# Exit
exit $STATUS
