#!/usr/bin/env bash

set -euo pipefail

if [[ "${SKIP_FRONTEND_ISLANDS_BUILD:=false}" == "true" ]]; then
  echo "Skipping frontend islands build, the variable SKIP_FRONTEND_ISLANDS_BUILD is set to true!"
  exit
fi

source "$(dirname "$0")/utils.sh"

function build_frontend_islands() {
  local original_dir=$(pwd)
  local fe_islands_dir="ee/frontend_islands"

  if [[ ! -d "ee/" ]]; then
    echo "Not building the frontend islands in FOSS only mode. Exiting early"
    return 0
  fi

  section_start "frontend-islands-check" "Checking for frontend islands"

  # Check if frontend islands directory exists
  if [ ! -d "${fe_islands_dir}/" ]; then
    echoinfo "No frontend islands found at ${fe_islands_dir}, skipping..."
    section_end "frontend-islands-check"
    return 0
  fi

  echoinfo "Found frontend islands directory, proceeding with build..."
  section_end "frontend-islands-check"

  # Install dependencies first using the dedicated script
  "$(dirname "$0")/install_frontend_islands"

  # Navigate to the frontend island
  cd "$fe_islands_dir"

  section_start "frontend-islands-build" "Building frontend island"
  # Use direct execution instead of retry to fail fast on build errors
  if ! yarn build:prod; then
    echoerr "Frontend island build failed. Failing fast to avoid blocking subsequent execution."
    cd "$original_dir"
    return 1
  fi
  section_end "frontend-islands-build"

  # Return to project root
  cd "$original_dir"
}

section_start "build-frontend-islands" "Building Frontend Islands"
build_frontend_islands
section_end "build-frontend-islands"
