#!/bin/sh
# Local development for aivis_os without PHP on the host. Everything runs in the
# Docker image from scripts/drupal-dev (Drupal 11.4, Drush, core-dev tools).
#
#   scripts/dev up          start the site on http://localhost:8096
#   scripts/dev site-install  fresh Drupal (SQLite, minimal profile); prints a login link
#   scripts/dev drush ...   run Drush in the site
#   scripts/dev phpunit [path]   unit tests (default: tests/src/Unit)
#   scripts/dev kernel [sqlite|mysql|mariadb|pgsql|all]   kernel tests (default: all)
#   scripts/dev e2e         bind and sync the dev site against the WordPress repo's mock API
#   scripts/dev functional  browser tests on real pages, inside the web container (SQLite)
#   scripts/dev phpcs       Drupal and DrupalPractice standards
#   scripts/dev phpstan     static analysis
#   scripts/dev cspell      spelling, with drupal.org's dictionaries plus .cspell-project-words.txt
#   scripts/dev next-major [unit|kernel]  the suite on the next major core (12.x, PHP 8.5, SQLite)
#   scripts/dev down        stop; add -v to drop the site volume
set -e
here="$(cd "$(dirname "$0")" && pwd)"
compose="docker compose -f $here/drupal-dev/docker-compose.yml"
mod=web/modules/contrib/aivis_os

run() { $compose run --rm --no-deps -T drupal sh -c "cd /opt/drupal && $*"; }
exec_site() { $compose exec -T drupal sh -c "cd /opt/drupal && $*"; }

cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
  up) $compose up -d --build ;;
  down) $compose down "$@" ;;
  site-install)
    $compose up -d
    exec_site "vendor/bin/drush -y site:install minimal --db-url=sqlite://localhost//opt/drupal/web/sites/default/files/.ht.sqlite --site-name='Aivis-OS dev' --account-name=admin 2>&1 | grep -v 'User password' && chown -R www-data:www-data web/sites/default/files && vendor/bin/drush uli --uri=http://localhost:8096"
    ;;
  drush) exec_site "vendor/bin/drush --uri=http://localhost:8096 $*" ;;
  phpunit)
    target="${1:-$mod/tests/src/Unit}"
    run "vendor/bin/phpunit -c web/core --colors=never $target"
    ;;
  kernel)
    which="${1:-all}"
    [ "$which" = all ] && which="sqlite mysql mariadb pgsql"
    failed=""
    for db in $which; do
      case "$db" in
        sqlite) url="sqlite://localhost//tmp/kernel.sqlite"; driver=sqlite ;;
        mysql) url="mysql://drupal:drupal@mysql/drupal"; driver=mysql ;;
        mariadb) url="mysql://drupal:drupal@mariadb/drupal"; driver=mysql ;;
        pgsql) url="pgsql://drupal:drupal@pgsql/drupal"; driver=pgsql ;;
        *) echo "unknown database: $db" >&2; exit 64 ;;
      esac
      if [ "$db" != sqlite ]; then
        $compose --profile db up -d --wait "$db" >/dev/null 2>&1
        [ "$db" = pgsql ] && $compose --profile db exec -T pgsql psql -q -U drupal -d drupal -c 'CREATE EXTENSION IF NOT EXISTS pg_trgm' >/dev/null
      fi
      echo "== kernel tests on $db"
      if out=$($compose run --rm --no-deps -T -e SIMPLETEST_DB="$url" -e AIVIS_EXPECT_DRIVER="$driver" drupal sh -c \
        "cd /opt/drupal && mkdir -p web/sites/simpletest && vendor/bin/phpunit -c web/core --colors=never $mod/tests/src/Kernel" 2>&1); then
        echo "$out" | grep -E '^(OK|Tests:)'
      else
        echo "$out" | grep -vE '^ *Container ' | tail -40
        failed="$failed $db"
      fi
    done
    [ -z "$failed" ] || { echo "kernel tests failed on:$failed" >&2; exit 1; }
    ;;
  functional)
    # BrowserTestBase drives Apache in the running container, so the tests run
    # there too, as www-data, sharing the SQLite file with the web server.
    $compose up -d >/dev/null 2>&1
    $compose exec -T drupal sh -c 'mkdir -p /opt/drupal/web/sites/simpletest/browser_output && chown -R www-data:www-data /opt/drupal/web/sites/simpletest && rm -f /tmp/functional.sqlite*'
    $compose exec -T -u www-data -e SIMPLETEST_BASE_URL=http://localhost -e SIMPLETEST_DB=sqlite://localhost//tmp/functional.sqlite \
      -e BROWSERTEST_OUTPUT_DIRECTORY=/tmp drupal sh -c \
      "cd /opt/drupal && vendor/bin/phpunit -c web/core --colors=never ${1:-$mod/tests/src/Functional}" | grep -vE '^http://localhost/sites/simpletest/browser_output|^HTML output was generated'
    ;;
  e2e)
    # The contract mock of the WordPress repository stays the arbiter of the
    # API shape (spec §20). AIVIS_WP_REPO points at a checkout of it.
    wp="${AIVIS_WP_REPO:-$here/../../aivis-wordpress-connector}"
    [ -f "$wp/tests/mock/server.js" ] || { echo "no mock API at $wp (set AIVIS_WP_REPO)" >&2; exit 1; }
    wp="$(cd "$wp" && pwd)"
    net="aivis-os-drupal-dev_default"
    $compose up -d >/dev/null 2>&1
    docker rm -f aivis-mock >/dev/null 2>&1 || true
    docker run -d --rm --name aivis-mock --network "$net" -v "$wp":/repo:ro -w /repo node:22-alpine node tests/mock/server.js >/dev/null
    trap 'docker rm -f aivis-mock >/dev/null 2>&1 || true' EXIT
    sleep 2
    d() { $compose exec -T drupal /opt/drupal/vendor/bin/drush --root=/opt/drupal --uri=https://example.com "$@"; }
    $compose exec -T drupal sh -c 'f=/opt/drupal/web/sites/default/settings.php; chmod u+w $f; grep -q aivis_os_api_base_url $f || printf "%s\n" "\$settings[\"aivis_os_api_base_url\"] = \"http://aivis-mock:8787\";" >> $f'
    d -y pmu aivis_os >/dev/null 2>&1 || true
    d -y en aivis_os >/dev/null
    # The business-bound fixture token of the mock; passed by environment, never printed.
    token="$(sed -n "s/^export const BOUND_TOKEN = '\([^']*\)' + '\([^']*\)';.*/\1\2/p" "$wp/tests/mock/data.js")"
    [ -n "$token" ] || { echo "fixture token not found in the mock data" >&2; exit 1; }
    $compose exec -T -e AIVIS_MOCK_TOKEN="$token" drupal /opt/drupal/vendor/bin/drush --root=/opt/drupal php:eval \
      '\Drupal::service("Drupal\\aivis_os\\Storage\\TokenProvider")->setStoredToken(getenv("AIVIS_MOCK_TOKEN"));'
    unset token
    d aivis:bind
    d aivis:languages assign chain_core en
    d aivis:sync --all
    got="$(d sqlq "SELECT source_url, chain_id FROM aivis_os_artifact WHERE active = 1 ORDER BY source_url" | tr -s '\n ' ' ' | sed 's/ *$//')"
    want="https://example.com/|chain_core https://example.com/altes-angebot/|chain_core https://example.com/en/|chain_en https://example.com/en/services/|chain_en https://example.com/services/|chain_core"
    echo "served: $got"
    [ "$got" = "$want" ] || { echo "e2e: expected $want" >&2; exit 1; }
    echo "e2e: OK"
    ;;
  phpcs)
    run "vendor/bin/phpcs --standard=Drupal,DrupalPractice --extensions=php,module,inc,install,test,profile,theme,info,yml --ignore=$mod/vendor,$mod/scripts/drupal-dev/build.log $mod"
    ;;
  phpstan) run "vendor/bin/phpstan analyse -c $mod/phpstan.neon --no-progress --memory-limit=1G" ;;
  next-major)
    # unit (default) or kernel. The kernel suite of core 12.0.0-beta2 itself
    # fails at container build (its DrupalDebugClassLoader and Symfony 8.1),
    # so CI runs that half without blocking until core fixes it.
    suite=Unit; [ "${1:-unit}" = kernel ] && suite=Kernel
    docker build -q -t aivis-os-drupal-next "$here/drupal-next" >/dev/null
    docker run --rm -v "$here/..":/opt/drupal/web/modules/contrib/aivis_os:ro -e SIMPLETEST_DB=sqlite://localhost//tmp/kernel.sqlite \
      aivis-os-drupal-next sh -c "php -v | head -1 && composer show drupal/core | grep ^versions && vendor/bin/phpunit -c web/core --colors=never $mod/tests/src/$suite"
    ;;
  cspell)
    # drupal.org's GitLab template checks spelling with core's dictionaries and
    # the project's word list; the same configuration runs here.
    core="$(mktemp -d)"
    trap 'rm -rf "$core"' EXIT
    run "cd web/core && tar cf - .cspell.json misc/cspell" | tar xf - -C "$core"
    docker run --rm -v "$here/..":/mod:ro -v "$core":/core:ro -w /mod node:22-alpine \
      npx -y cspell@8.19.4 lint --no-progress --show-suggestions -c scripts/cspell.json "**"
    ;;
  *) sed -n '2,15p' "$0"; exit 64 ;;
esac
