#!/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_island_dir="ee/frontend_islands/apps/duo_next"

  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 "ee/frontend_islands/apps/duo_next" ]; then
    echoinfo "No frontend islands found at ee/frontend_islands/apps/duo_next, skipping..."
    section_end "frontend-islands-check"
    return 0
  fi

  # Check if frontend islands's dependencies are installed
  # Checking for the integrity file instead of just the folder that can be empty
  if [ ! -f "ee/frontend_islands/apps/duo_next/node_modules/.yarn-integrity" ]; then
    echoinfo "Frontend islands dependencies not found, installing..."
    cd "$fe_island_dir"
    retry yarn install --frozen-lockfile
    cd "$original_dir"
  fi

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

  # Navigate to the frontend island
  cd "$fe_island_dir"

  section_start "frontend-islands-build" "Building frontend island"
  retry yarn build:prod
  section_end "frontend-islands-build"

  # Verify the build output
  if [ -f "dist/duo_next.js" ]; then
    local file_size=$(du -h dist/duo_next.js | cut -f1)
    echosuccess "Frontend island built successfully at: $(pwd)/dist/duo_next.js (${file_size})"
  else
    echoerr "Expected build output not found at dist/duo_next.js"
    cd "$original_dir"
    return 1
  fi

  # Return to project root
  cd "$original_dir"
}

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