#!/usr/bin/env bash
# One-shot local setup. Run from Git Bash or WSL:
#   bash docker/setup.sh [path/to/dump.sql | dump.sql.gz]
# Without a dump it reuses whatever is already in the docker database.
set -euo pipefail
export MSYS_NO_PATHCONV=1   # stop Git Bash from rewriting container paths
cd "$(dirname "$0")/.."

DUMP="${1:-}"
APP_URL="http://localhost:${HTTP_PORT:-8080}/"

dc()  { docker compose "$@"; }
app() { dc exec -T -u www-data -e APP_URL="$APP_URL" app "$@"; }
sql() { dc exec -T db mariadb -uroot -proot magento "$@"; }

if [ ! -f app/etc/env.php ]; then
  echo "app/etc/env.php is missing. Copy it from dev/staging first: it holds the crypt key." >&2
  exit 1
fi
if [ -n "$DUMP" ] && [ ! -f "$DUMP" ]; then
  echo "Dump file not found: $DUMP" >&2
  exit 1
fi

echo "==> Building and starting containers"
dc up -d --build --wait

if [ -n "$DUMP" ]; then
  echo "==> Importing $DUMP (this can take a while)"
  sql -e "DROP DATABASE magento; CREATE DATABASE magento; GRANT ALL ON magento.* TO 'magento'@'%';"
  case "$DUMP" in
    *.gz) reader=(gunzip -c "$DUMP") ;;
    *)    reader=(cat "$DUMP") ;;
  esac
  # Strip DEFINER clauses: production DB users don't exist locally.
  "${reader[@]}" | sed -E 's/DEFINER=`[^`]+`@`[^`]+`//g' | sql
fi

if [ -z "$(sql -N -e "SHOW TABLES LIKE 'core_config_data'")" ]; then
  echo "The docker database is empty. Re-run with a dump: bash docker/setup.sh path/to/dump.sql.gz" >&2
  exit 1
fi

echo "==> Pointing env.php and store URLs at docker"
app php docker/bin/configure-env.php
sql <<SQL
UPDATE core_config_data SET value = '$APP_URL'
 WHERE path IN ('web/unsecure/base_url','web/secure/base_url','web/unsecure/base_link_url','web/secure/base_link_url');
UPDATE core_config_data SET value = '0'
 WHERE path IN ('web/secure/use_in_frontend','web/secure/use_in_adminhtml','web/secure/enable_hsts','web/secure/enable_upgrade_insecure');
DELETE FROM core_config_data
 WHERE path IN ('web/cookie/cookie_domain','web/unsecure/base_static_url','web/secure/base_static_url',
                'web/unsecure/base_media_url','web/secure/base_media_url');
SQL

if [ ! -f vendor/autoload.php ]; then
  echo "==> vendor/ missing, running composer install (re-apply the vendor patches from README.md afterwards)"
  app composer install --no-interaction
fi

echo "==> setup:upgrade, reindex, cache flush"
app bin/magento setup:upgrade
app bin/magento indexer:reindex
app bin/magento cache:flush

admin_path=$(app php -r '$e = require "app/etc/env.php"; echo $e["backend"]["frontName"] ?? "admin";')
cat <<MSG

Done.
  Store / GraphQL : ${APP_URL}  (${APP_URL}graphql)
  Admin           : ${APP_URL}${admin_path}
  Mailpit         : http://localhost:${MAILPIT_PORT:-8025}
  DB from host    : localhost:${DB_PORT:-3307}  magento / magento

Create an admin user: bash docker/magento.sh admin:user:create
MSG
