#!/usr/bin/env bash
# Stand-in for the lilbee entrypoint that tools/qa/artifact_smoke.sh drives.
# Records every subcommand and answers the smoke's two searches from a canned map.
#
# Reads:
#   SMOKE_CALLS          file each subcommand is appended to (required)
#   SMOKE_CRAWL_INDEXED  1 when the crawled page is searchable (default: 1)
#   SMOKE_FAIL_LEG       leg that prints an error on stdout and exits 3
#                        (search, ask, crawl, browser or browser-search; default: none)
#   SMOKE_NO_BROWSER      1 when a browser-mode add ignores the setting and
#                        installs no Chromium (default: 0)
#   SMOKE_BROWSER_INDEXED  1 when the browser-mode crawl is searchable (default: 1)

set -euo pipefail

if [ "${1:-}" = "--data-dir" ]; then
  shift 2
fi
sub="${1:-}"
shift || true

echo "${sub} $* [render=${LILBEE_CRAWL_RENDER_MODE:-}]" >> "${SMOKE_CALLS:?SMOKE_CALLS is required}"

# The real CLI prints its errors on stdout, which is what the captured legs
# discard when the command substitution takes the script down with it.
fail_leg() {  # leg
  [ "${SMOKE_FAIL_LEG:-}" = "$1" ] || return 0
  echo "Error: the ${1} leg could not reach the engine"
  exit 3
}

case "${sub}" in
  add)
    case "${1:-}" in
      http*)
        if [ "${LILBEE_CRAWL_RENDER_MODE:-}" = "browser" ]; then
          fail_leg browser
          if [ "${SMOKE_NO_BROWSER:-0}" != "1" ]; then
            mkdir -p "${PLAYWRIGHT_BROWSERS_PATH:?}/chromium_headless_shell-1000"
            : > "${PLAYWRIGHT_BROWSERS_PATH}/chromium_headless_shell-1000/INSTALLATION_COMPLETE"
          fi
        fi
        ;;
    esac
    ;;
  search)
    case "${1:-}" in
      *quartz*)
        fail_leg search
        echo "1. smoke-doc.md   blue quartz resonator array"
        ;;
      *"use in documentation"*)
        fail_leg browser-search
        if [ "${SMOKE_BROWSER_URL_ONLY:-0}" = "1" ]; then
          echo "1. https://example.com"
        elif [ "${SMOKE_BROWSER_INDEXED:-1}" = "1" ]; then
          echo "1. https://example.com   This domain is for use in documentation examples without needing permission."
        fi
        ;;
      *"use in examples"*)
        fail_leg crawl
        if [ "${SMOKE_CRAWL_INDEXED:-1}" = "1" ]; then
          echo "1. https://example.com   This domain is for use in documentation examples without needing permission."
        fi
        ;;
    esac
    ;;
  ask)
    fail_leg ask
    echo "The blue quartz resonator is calibrated to 432 megahertz."
    ;;
esac
