#!/usr/bin/env bash
#
# Install / refresh the root SEO discovery bridge (robots.txt, sitemaps, merchant
# feeds) in a docroot .htaccess:
#
#   projects/storefront/deploy/install-root-seo-bridge.sh <docroot>/.htaccess [owner]
#
# robots.txt and the sitemaps belong at the origin root, outside /store/ and
# /website/. The managed block (root-seo-bridge.template, between the BEGIN/END
# markers) is written at the TOP of the file so an existing catch-all cannot consume
# these requests first; tenant rules outside the block survive untouched. Called by
# both the storefront and the website deploy scripts (either public module needs it).

set -euo pipefail

ROOT_HTACCESS="${1:?usage: install-root-seo-bridge.sh <root .htaccess> [owner]}"
OWNER="${2:-}"
TEMPLATE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/root-seo-bridge.template"

[ -f "$TEMPLATE" ] || { echo "FATAL: $TEMPLATE is missing"; exit 1; }
[ -d "$(dirname "$ROOT_HTACCESS")" ] || { echo "FATAL: $(dirname "$ROOT_HTACCESS") does not exist"; exit 1; }

# Refuse a damaged managed block: an orphan BEGIN would make the filter below drop every
# tenant rule after it; CRLF markers would not match and the block would be duplicated.
if [ -f "$ROOT_HTACCESS" ]; then
  if grep -q $'\r' "$ROOT_HTACCESS"; then
    echo "FATAL: $ROOT_HTACCESS has CRLF line endings — convert it to LF first"
    exit 1
  fi
  BEGINS="$(grep -c '^# BEGIN Moon Storefront SEO Discovery$' "$ROOT_HTACCESS" || true)"
  ENDS="$(grep -c '^# END Moon Storefront SEO Discovery$' "$ROOT_HTACCESS" || true)"
  if [ "$BEGINS" != "$ENDS" ]; then
    echo "FATAL: $ROOT_HTACCESS has $BEGINS BEGIN and $ENDS END markers — fix it by hand first"
    exit 1
  fi
fi

ROOT_TMP="$(mktemp "$(dirname "$ROOT_HTACCESS")/.htaccess.moon-seo.XXXXXX")"
trap 'rm -f "$ROOT_TMP"' EXIT
{
  cat "$TEMPLATE"
  if [ -f "$ROOT_HTACCESS" ]; then
    awk '
      /^# BEGIN Moon Storefront SEO Discovery$/ { managed=1; next }
      /^# END Moon Storefront SEO Discovery$/ { managed=0; next }
      !managed { print }
    ' "$ROOT_HTACCESS"
  fi
} > "$ROOT_TMP"
if [ -f "$ROOT_HTACCESS" ]; then
  chmod --reference="$ROOT_HTACCESS" "$ROOT_TMP"
else
  chmod 644 "$ROOT_TMP"
fi
mv "$ROOT_TMP" "$ROOT_HTACCESS"
trap - EXIT

if [ -n "$OWNER" ]; then
  chown "$OWNER:$OWNER" "$ROOT_HTACCESS"
fi

grep -q '^# BEGIN Moon Storefront SEO Discovery$' "$ROOT_HTACCESS" || {
  echo "FATAL: root SEO discovery bridge is missing from $ROOT_HTACCESS"
  exit 1
}
echo "    root bridge   : $ROOT_HTACCESS"
