#!/bin/bash

## Description: Initialize Storybook for Varbase.
## Usage: init-storybook
## Example: ddev init-storybook
## Aliases: varbase:storybook

echo "Initializing Storybook for Varbase..."

# Install necessary dependencies for Storybook.
yarn install

# Store the current working directory path for later use.
current_path=$(pwd);

# Resolve dynamic host names for this project.
# Example: DDEV_HOSTNAME=varbase.ddev.site -> STORYBOOK_HOST=storybook.varbase.ddev.site
CURRENT_HOST="${DDEV_HOSTNAME:-${DDEV_PRIMARY_URL_WITHOUT_PORT#https://}}"
# DDEV_HOSTNAME may contain a comma-separated list; use only the first host.
CURRENT_HOST="${CURRENT_HOST%%,*}"
CURRENT_HOST="${CURRENT_HOST#https://}"
CURRENT_HOST="${CURRENT_HOST#http://}"
CURRENT_HOST="${CURRENT_HOST%%/*}"
CURRENT_HOST="${CURRENT_HOST%%:*}"
STORYBOOK_HOST="storybook.${CURRENT_HOST#storybook.}"

# Enable the Storybook module in Drupal.
drush pm:enable storybook

# Grant "render storybook stories" permission to both anonymous and authenticated users.
drush role:perm:add anonymous 'render storybook stories'
drush role:perm:add authenticated 'render storybook stories'

# ---------------------------------------------------------------------------
# Switch on the development local services for Storybook.
# Copies development.local.services.yml and enables it in settings.ddev.php.
# This file enables CORS (all origins), Twig debug, and storybook.development.
# ---------------------------------------------------------------------------

# Copy the development.local.services.yml template into place and enable the
# include in the Drupal settings files. Delegated to `ddev storybook enable`,
# which is ALSO run from the post-start hook in .ddev/config.yaml - because DDEV
# regenerates settings.ddev.php on every start and would otherwise drop this
# include, silently breaking cross-origin story rendering (CORS) after a restart.
bash "${current_path}/.ddev/commands/web/storybook" enable

# ---------------------------------------------------------------------------
# Update Storybook hostname in DDEV config and Apache proxy config.
# This keeps subdomain routing aligned with the current project hostname.
# ---------------------------------------------------------------------------

DDEV_CONFIG_FILE="${current_path}/.ddev/config.yaml"
APACHE_PROXY_FILE="${current_path}/.ddev/apache/storybook-proxy.conf"

if [[ -f "${DDEV_CONFIG_FILE}" ]]; then
  if grep -qE '^[[:space:]]*additional_fqdns:[[:space:]]*$' "${DDEV_CONFIG_FILE}"; then
    awk -v host="${STORYBOOK_HOST}" '
      /^[[:space:]]*additional_fqdns:[[:space:]]*$/ {
        print $0;
        in_fqdns=1;
        next;
      }
      in_fqdns && /^[[:space:]]*-[[:space:]]*/ {
        if ($0 ~ /^[[:space:]]*-[[:space:]]*storybook\./) {
          if (!done) {
            print "  - " host;
            done=1;
          }
          next;
        }
        print $0;
        next;
      }
      in_fqdns && !/^[[:space:]]*-[[:space:]]*/ {
        if (!done) {
          print "  - " host;
          done=1;
        }
        in_fqdns=0;
      }
      { print $0 }
      END {
        if (in_fqdns && !done) {
          print "  - " host;
        }
      }
    ' "${DDEV_CONFIG_FILE}" > "${DDEV_CONFIG_FILE}.tmp" && mv "${DDEV_CONFIG_FILE}.tmp" "${DDEV_CONFIG_FILE}"
  else
    awk -v host="${STORYBOOK_HOST}" '
      /^[[:space:]]*use_dns_when_possible:[[:space:]]*/ && !done {
        print $0;
        print "additional_fqdns:";
        print "  - " host;
        done=1;
        next;
      }
      { print $0 }
    ' "${DDEV_CONFIG_FILE}" > "${DDEV_CONFIG_FILE}.tmp" && mv "${DDEV_CONFIG_FILE}.tmp" "${DDEV_CONFIG_FILE}"
  fi
  echo "Configured additional_fqdns host: ${STORYBOOK_HOST}"
fi

if [[ -f "${APACHE_PROXY_FILE}" ]]; then
  sed -i -E "s#^([[:space:]]*ServerName[[:space:]]+)storybook\.[[:alnum:].-]+#\\1${STORYBOOK_HOST}#" "${APACHE_PROXY_FILE}"
  echo "Updated Apache Storybook ServerName to: ${STORYBOOK_HOST}"
fi

# ---------------------------------------------------------------------------
# Write .env.storybook with the correct Drupal server URLs (port-aware).
# STORYBOOK_SERVER_URL      — Drupal base URL (with port when non-443)
# STORYBOOK_SERVER_RENDER_URL — Drupal Storybook render endpoint
# These are loaded by storybook:dev and storybook:build scripts via sh.
# ---------------------------------------------------------------------------

PORT="${DDEV_ROUTER_HTTPS_PORT:-443}"
BASE="${DDEV_PRIMARY_URL_WITHOUT_PORT}"
if [ "$PORT" = "443" ]; then
  DRUPAL_URL="${BASE}"
else
  DRUPAL_URL="${BASE}:${PORT}"
fi

echo "STORYBOOK_SERVER_URL=${DRUPAL_URL}" > "${current_path}/.env.storybook"
echo "STORYBOOK_SERVER_RENDER_URL=${DRUPAL_URL}/storybook/stories/render" >> "${current_path}/.env.storybook"
echo "Storybook URLs written to .env.storybook:"
cat "${current_path}/.env.storybook"

# Rebuild Drupal cache to apply service changes.
drush cache:rebuild
echo "Drupal cache rebuilt."
echo ""
echo ""
echo "Access Storybook at:"
echo "   • https://${STORYBOOK_HOST}/"
echo "   • https://${CURRENT_HOST}:6006/"
echo ""

echo "Storybook initialized."
echo ""
echo "The Storybook dev server runs automatically as a DDEV web_extra_daemon"
echo "(see web_extra_daemons in .ddev/config.yaml) - you do NOT need to start it"
echo "manually. It is already serving on port 6006 and the subdomain above."
echo ""
echo "If the subdomain or port changed during init, run 'ddev restart' once to"
echo "apply the updated routing, then reload the Storybook URL."
echo ""
echo "Useful commands:"
echo "   • ddev yarn storybook:ddev     # (re)start the Storybook dev server manually"
echo "   • ddev yarn storybook:gen      # regenerate *.stories.json from Twig"
echo "   • ddev yarn storybook:build    # build static Storybook into ./storybook"
echo "   • ddev restart                 # apply hostname/routing changes"
echo "   • ddev logs -f | grep -i story # follow the Storybook daemon log"
