#!/usr/bin/env bash

# setup.sh - Prepare the GitLab Rails monolith for local Caproni development.
#
# Copies runtime configuration generated by CNG / the Helm chart from a live
# gitlab-webservice-default pod into the local checkout, then rewrites the
# Rails environment from "production" to "development" so the app can run
# locally (e.g. via mirrord) against the real cluster services.
#
# Only files that are generated at deploy time (i.e. NOT committed to the
# gitlab-rails repo) are fetched.  See the CONFIG_FILES list in section 2.
#
# Prerequisites:
#   - kubectl configured and pointing at the Caproni cluster
#   - A running gitlab-webservice-default deployment in the target namespace
#   - The GitLab Rails repo checked out locally
#
# Usage:
#   .gitlab/caproni/setup.sh [--namespace <ns>] [--context <kubectl-context>]

set -euo pipefail

# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# Helper functions for colored output
error() {
  echo >&2 -e "${RED}ERROR: ${1-}${NC}"
}

warn() {
  echo >&2 -e "${YELLOW}WARNING: ${1-}${NC}"
}
success(){
  echo >&2 -e "${GREEN} ${1-}${NC}"
}

# Relies on globals: KUBECTL, NAMESPACE, PG_POD, PG_PASS.
create_db_from_production() {
  local db_name="$1"

  echo ""
  echo "==> Creating $db_name database (if it does not exist)..."

  local db_exists
  db_exists=$($KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
    env PGPASSWORD="$PG_PASS" psql -U postgres -d postgres -tAc \
      "SELECT 1 FROM pg_database WHERE datname='$db_name'" 2>/dev/null || true)

  if [[ "$db_exists" =~ 1 ]]; then
    echo "  ✓ $db_name already exists – skipping creation."
    return 0
  fi

  echo "  Terminating active sessions on gitlabhq_production..."
  local terminated
  terminated=$($KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
    env PGPASSWORD="$PG_PASS" psql -U postgres -d postgres -tAc \
      "SELECT count(*) FROM (SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='gitlabhq_production' AND pid <> pg_backend_pid()) t" || echo "?")
  echo "  Terminated $terminated sessions."

  echo "  Creating $db_name from template gitlabhq_production..."
  if $KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
    env PGPASSWORD="$PG_PASS" psql -U postgres -d postgres -c \
      "CREATE DATABASE \"$db_name\" TEMPLATE gitlabhq_production OWNER gitlab"; then
    success "  ✓ $db_name created successfully."
  else
    error "Failed to create $db_name."
    exit 1
  fi
}


# ---------------------------------------------------------------------------
# 0. Parse arguments / set defaults

NAMESPACE="${NAMESPACE:-gitlab}"
KUBE_CONTEXT=""
GITLAB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
POD_BASE="/srv/gitlab"
DEPLOYMENT_LABEL="app=webservice"
CONTAINER="webservice"
SIDEKIQ_DEPLOYMENT_LABEL="app=sidekiq"
SIDEKIQ_CONTAINER="sidekiq"
WORKHORSE_CONTAINER="gitlab-workhorse"


while [[ $# -gt 0 ]]; do
  case "$1" in
    --namespace)
      NAMESPACE="$2"
      shift 2
      ;;
    --context)
      KUBE_CONTEXT="$2"
      shift 2
      ;;
    *)
      echo "Unknown argument: $1" >&2
      echo "Usage: $0 [--namespace <ns>] [--context <kubectl-context>]" >&2
      exit 1
      ;;
  esac
done

KUBECTL="kubectl"
if [[ -n "$KUBE_CONTEXT" ]]; then
  KUBECTL="kubectl --context=$KUBE_CONTEXT"
fi

echo "==> GitLab directory : $GITLAB_DIR"
echo "==> Namespace        : $NAMESPACE"
[[ -n "$KUBE_CONTEXT" ]] && echo "==> Context          : $KUBE_CONTEXT"

# ---------------------------------------------------------------------------
# 1. Locate a running pod from the gitlab-webservice-default deployment
#    Picks the first Running pod; aborts if none is found.
# ---------------------------------------------------------------------------

echo ""
echo "==> Locating a running pod in $NAMESPACE with label $DEPLOYMENT_LABEL..."

POD_NAME=""
MAX_RETRIES=120
RETRY_INTERVAL=2
ATTEMPT=0

# Waiting for pod to be found with label webservice
# Logs pod name and status along with namespace if the pod is found but with status other than Running
# Logs "Pod not found with label <label> in naespace <namespace>, retrying in Xs (attempt x/y)" if pod not found
while [[ $ATTEMPT -lt $MAX_RETRIES ]]; do
  POD_NAME=$(
    $KUBECTL get pod -n "$NAMESPACE" \
      -l "$DEPLOYMENT_LABEL" \
      -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true
  )

  if [[ -z "$POD_NAME" ]]; then
    ATTEMPT=$((ATTEMPT + 1))
    if [[ $ATTEMPT -lt $MAX_RETRIES ]]; then
      echo "Pod not found with label $DEPLOYMENT_LABEL in namespace $NAMESPACE, retrying in ${RETRY_INTERVAL}s (attempt $ATTEMPT/$MAX_RETRIES)..."
      sleep "$RETRY_INTERVAL"
    fi
    continue
  fi

  POD_STATUS=$(
    $KUBECTL get pod -n "$NAMESPACE" \
      -l "$DEPLOYMENT_LABEL" \
      -o jsonpath='{.items[0].status.phase}' 2>/dev/null || true
  )

  if [[ "$POD_STATUS" == "Running" ]]; then
    success "==> Found pod: $POD_NAME in $POD_STATUS status"
    break
  fi

  ATTEMPT=$((ATTEMPT + 1))
  if [[ $ATTEMPT -lt $MAX_RETRIES ]]; then
    echo "Pod $POD_NAME status: $POD_STATUS, retrying in ${RETRY_INTERVAL}s (attempt $ATTEMPT/$MAX_RETRIES)..."
    sleep "$RETRY_INTERVAL"
  fi
done

if [[ -z "$POD_NAME" ]] || [[ "$POD_STATUS" != "Running" ]]; then
  error "No Running webservice pod found in namespace '$NAMESPACE' after $((MAX_RETRIES * RETRY_INTERVAL))s."
  error "       Check: kubectl get pods -n $NAMESPACE -l app=webservice" >&2
  exit 1
fi

# ---------------------------------------------------------------------------
# 1b. Locate a running pod from the gitlab-sidekiq-all-in-1-v2 deployment
# ---------------------------------------------------------------------------

echo ""
echo "==> Locating a running pod in $NAMESPACE with label $SIDEKIQ_DEPLOYMENT_LABEL..."

SIDEKIQ_POD_NAME=""
ATTEMPT=0

while [[ $ATTEMPT -lt $MAX_RETRIES ]]; do
  SIDEKIQ_POD_NAME=$(
    $KUBECTL get pod -n "$NAMESPACE" \
      -l "$SIDEKIQ_DEPLOYMENT_LABEL" \
      -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true
  )

  if [[ -z "$SIDEKIQ_POD_NAME" ]]; then
    ATTEMPT=$((ATTEMPT + 1))
    if [[ $ATTEMPT -lt $MAX_RETRIES ]]; then
      echo "Pod not found with label $SIDEKIQ_DEPLOYMENT_LABEL in namespace $NAMESPACE, retrying in ${RETRY_INTERVAL}s (attempt $ATTEMPT/$MAX_RETRIES)..."
      sleep "$RETRY_INTERVAL"
    fi
    continue
  fi

  SIDEKIQ_POD_STATUS=$(
    $KUBECTL get pod -n "$NAMESPACE" \
      -l "$SIDEKIQ_DEPLOYMENT_LABEL" \
      -o jsonpath='{.items[0].status.phase}' 2>/dev/null || true
  )

  if [[ "$SIDEKIQ_POD_STATUS" == "Running" ]]; then
    success "==> Found pod: $SIDEKIQ_POD_NAME in $SIDEKIQ_POD_STATUS status"
    break
  fi

  ATTEMPT=$((ATTEMPT + 1))
  if [[ $ATTEMPT -lt $MAX_RETRIES ]]; then
    echo "Pod $SIDEKIQ_POD_NAME status: $SIDEKIQ_POD_STATUS, retrying in ${RETRY_INTERVAL}s (attempt $ATTEMPT/$MAX_RETRIES)..."
    sleep "$RETRY_INTERVAL"
  fi
done

if [[ -z "$SIDEKIQ_POD_NAME" ]] || [[ "$SIDEKIQ_POD_STATUS" != "Running" ]]; then
  error "No Running sidekiq pod found in namespace '$NAMESPACE' after $((MAX_RETRIES * RETRY_INTERVAL))s."
  error "       Check: kubectl get pods -n $NAMESPACE -l $SIDEKIQ_DEPLOYMENT_LABEL" >&2
  exit 1
fi

# ---------------------------------------------------------------------------
# 2. Copy CNG-generated config files from the pod into $CONFIG_DIR
#
#    These files are written by the Helm chart init containers or the CNG
#    image at pod startup and are NOT committed to the gitlab-rails repo.
#    Paths in CONFIG_FILES are relative to $POD_BASE (/srv/gitlab) in the pod
#    and are mirrored to the same relative path under $GITLAB_DIR locally.
# ---------------------------------------------------------------------------

echo ""
echo "==> Copying CNG-generated config files from pod $POD_NAME..."

CONFIG_FILES=(
  "config/gitlab.yml"
  "config/database.yml"
  "config/cable.yml"
  "config/resque.yml"
  "config/redis.action_cable.yml"
  "config/session_store.yml"
  "config/secrets.yml"
  "config/initializers/smtp_settings.rb"
  "config/puma.rb"
)

COPIED_FILES=()
FAILED_FILES=()

for file in "${CONFIG_FILES[@]}"; do
  local_path="$GITLAB_DIR/$file"
  mkdir -p "$(dirname "$local_path")"
  $KUBECTL cp -n "$NAMESPACE" -c "$CONTAINER" "$POD_NAME:$POD_BASE/$file" "$local_path" >/dev/null
  if [[ -f "$local_path" ]]; then
    echo "  ✓ $file"
    COPIED_FILES+=("$file")
  else
    warn "could not copy $file (skipping)"
    FAILED_FILES+=("$file")
  fi
done

echo "Copied ${#COPIED_FILES[@]} files, skipped ${#FAILED_FILES[@]}."

# ---------------------------------------------------------------------------
# 2b. Copy config/gitlab.yml from the sidekiq pod → local config/gitlab-sidekiq.yml
# ---------------------------------------------------------------------------

echo ""
echo "==> Copying config/gitlab.yml from sidekiq pod $SIDEKIQ_POD_NAME → config/gitlab-sidekiq.yml..."

SIDEKIQ_GITLAB_YML="$GITLAB_DIR/config/gitlab-sidekiq.yml"
mkdir -p "$(dirname "$SIDEKIQ_GITLAB_YML")"
$KUBECTL cp -n "$NAMESPACE" -c "$SIDEKIQ_CONTAINER" \
  "$SIDEKIQ_POD_NAME:$POD_BASE/config/gitlab.yml" "$SIDEKIQ_GITLAB_YML" >/dev/null 2>&1

if [[ -f "$SIDEKIQ_GITLAB_YML" ]]; then
  echo "  ✓ config/gitlab-sidekiq.yml"
else
  warn "could not copy config/gitlab.yml from sidekiq pod (skipping)"
fi

# ---------------------------------------------------------------------------
# 2c. Patch gitlab-sidekiq.yml: replace address: "*" with address: "0.0.0.0"
#
#     Under mirrord, getaddrinfo("*") is intercepted and forwarded to the
#     cluster's CoreDNS, which cannot resolve "*" → "Name or service not
#     known".  Replacing with the explicit bind-all address "0.0.0.0" avoids
#     any DNS lookup entirely and lets WEBrick bind correctly.
# ---------------------------------------------------------------------------

echo ""
echo "==> Patching config/gitlab-sidekiq.yml: replacing address: \"*\" with address: \"0.0.0.0\"..."

if [[ -f "$SIDEKIQ_GITLAB_YML" ]]; then
  sed -i.bak 's/^\([ \t]*address:\) "\*"$/\1 "0.0.0.0"/' "$SIDEKIQ_GITLAB_YML"
  rm "$SIDEKIQ_GITLAB_YML.bak"
  echo "  ✓ config/gitlab-sidekiq.yml"
else
  warn "config/gitlab-sidekiq.yml not found – skipping address patch"
fi

# ---------------------------------------------------------------------------
# 2d. Copy workhorse config and secret from the pod
#
#     The workhorse config lives in the gitlab-workhorse container, while
#     the workhorse secret is mounted in the webservice container.  Both
#     are generated at deploy time by the Helm chart and are not committed
#     to the repo.
# ---------------------------------------------------------------------------

echo ""
echo "==> Copying workhorse config and secret from pod $POD_NAME..."

CONTAINER_FILE_CONTAINERS=(
  "$WORKHORSE_CONTAINER"
  "$CONTAINER"
)
CONTAINER_FILE_POD_PATHS=(
  "/srv/gitlab/config/workhorse-config.toml"
  "/etc/gitlab/gitlab-workhorse/secret"
)
CONTAINER_FILE_LOCAL_PATHS=(
  "workhorse/workhorse-config.toml"
  ".gitlab_workhorse_secret"
)

for i in "${!CONTAINER_FILE_CONTAINERS[@]}"; do
  container="${CONTAINER_FILE_CONTAINERS[$i]}"
  pod_path="${CONTAINER_FILE_POD_PATHS[$i]}"
  local_rel="${CONTAINER_FILE_LOCAL_PATHS[$i]}"
  local_path="$GITLAB_DIR/$local_rel"
  mkdir -p "$(dirname "$local_path")"
  $KUBECTL cp -n "$NAMESPACE" -c "$container" "$POD_NAME:$pod_path" "$local_path" >/dev/null
  if [[ -f "$local_path" ]]; then
    echo "  ✓ $local_rel"
    COPIED_FILES+=("$local_rel")
  else
    warn "could not copy $local_rel (skipping)"
    FAILED_FILES+=("$local_rel")
  fi
done


# ---------------------------------------------------------------------------
# 3. Rewrite top-level "production:" key → "development:" in YAML configs
#
#    The Helm chart generates YAML files keyed under "production:".
#    Rails uses the top-level key to select the active config block, so
#    we rename it to "development:" to match RAILS_ENV=development.
#
#    Only the top-level key is replaced (anchored to start-of-line) so that
#    the word "production" inside values (e.g. log paths, URLs) is untouched.
# ---------------------------------------------------------------------------

echo ""
echo "==> Rewriting 'production:' → 'development:' in YAML config files..."

ENV_REWRITE_FILES=(
  "config/gitlab.yml"
  "config/gitlab-sidekiq.yml"
  "config/database.yml"
  "config/cable.yml"
  "config/resque.yml"
  "config/redis.action_cable.yml"
  "config/session_store.yml"
  "config/secrets.yml"
)

MODIFIED_FILES=()
UNMODIFIED_FILES=()

for file in "${ENV_REWRITE_FILES[@]}"; do
  file_path="$GITLAB_DIR/$file"
  if [[ -f "$file_path" ]]; then
    sed -i.bak 's/^production:/development:/' "$file_path"
    rm "$file_path.bak"
    MODIFIED_FILES+=("$file")
    echo "  - $file"
  else
    warn "unable to patch $file (skipping)"
    UNMODIFIED_FILES+=("$file")
  fi
done

echo "Rewrote environment key in ${#MODIFIED_FILES[@]} files."

# ---------------------------------------------------------------------------
# 4. Patch database.yml: add gssencmode: disable
#
#    libpq's GSSAPI negotiation triggers a segfault on macOS when connecting
#    to a PostgreSQL server that doesn't support GSSAPI (e.g. CloudNativePG).
#    Setting gssencmode: disable skips the negotiation entirely.
# ---------------------------------------------------------------------------

echo ""
echo "==> Patching config/database.yml: adding gssencmode: disable..."

DB_YML="$GITLAB_DIR/config/database.yml"
if [[ -f "$DB_YML" ]]; then
  # Insert "gssencmode: disable" on the line after every "adapter: postgresql",
  # preserving the same leading whitespace.  The sed expression is POSIX-
  # compatible and works on both GNU sed (Linux) and BSD sed (macOS).
  #
  sed -i.bak 's/^\([ \t]*\)adapter: postgresql$/\1adapter: postgresql\n\1gssencmode: disable/' "$DB_YML"
  rm "$DB_YML.bak"
  echo "  ✓ config/database.yml"
else
  warn "config/database.yml not found – skipping gssencmode patch"
fi

# ---------------------------------------------------------------------------
# 5. Copy gitlabhq_production → gitlabhq_development if it does not exist
#
#    We exec into the PostgreSQL pod and create the
#    database as a template copy of gitlabhq_production (after terminating
#    active sessions on the source).  The database.yml is then rewritten
#    to reference gitlabhq_development. This is signficantly faster than
#    pd_dump/pg_restore or loading the schema, due to avoiding Rails.
# ---------------------------------------------------------------------------

echo ""
echo "==> Locating PostgreSQL pod..."

PG_POD=$($KUBECTL get pod -n "$NAMESPACE" -l app.kubernetes.io/name=postgresql \
  -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)

if [[ -z "$PG_POD" ]]; then
  error "No PostgreSQL pod found in namespace '$NAMESPACE'."
  error "Check: $KUBECTL get pods -n $NAMESPACE -l app.kubernetes.io/name=postgresql"
  exit 1
fi

echo "  Found PostgreSQL pod: $PG_POD"

PG_PASS=$($KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
  sh -c 'echo "$POSTGRES_POSTGRES_PASSWORD"' 2>/dev/null || true)

if [[ -z "$PG_PASS" ]]; then
  error "Could not read POSTGRES_POSTGRES_PASSWORD from pod $PG_POD."
  exit 1
fi

AUTH_CHECK=$($KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
  env PGPASSWORD="$PG_PASS" psql -U postgres -tAc "SELECT 1" 2>&1 || true)

if [[ "$AUTH_CHECK" != "1" ]]; then
  error "PostgreSQL authentication failed. psql output:"
  error "$AUTH_CHECK"
  exit 1
fi

success "  Authentication OK"

create_db_from_production gitlabhq_development

# ---------------------------------------------------------------------------
# 5a. Drop amcheck from gitlabhq_development
#
#     amcheck is installed on cluster prod and rides along into
#     gitlabhq_development via the TEMPLATE clone. We drop it so it doesn't
#     propagate further (e.g. into template1 via the mirror step below).
#     Idempotent: IF EXISTS makes this a no-op when absent, so it runs
#     unconditionally — whether gitlabhq_development was created in this
#     invocation or already existed.
# ---------------------------------------------------------------------------

echo ""
echo "==> Dropping amcheck extension from gitlabhq_development..."

if $KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
  env PGPASSWORD="$PG_PASS" psql -U postgres -d gitlabhq_development -c \
    "DROP EXTENSION IF EXISTS amcheck;" >/dev/null; then
  echo "  ✓ amcheck dropped (or already absent)"
else
  error "Failed to drop amcheck extension from gitlabhq_development."
  exit 1
fi

# ---------------------------------------------------------------------------
# 5b. Mirror gitlabhq_development extensions into template1
#
#     RSpec creates gitlabhq_test by cloning template1 and then replays
#     db/structure.sql.  Extensions copied from cluster prod (e.g. btree_gist)
#     end up in structure.sql, and the replay fails because the test role
#     is not a superuser.  Pre-installing the same extensions into
#     template1 makes the `CREATE EXTENSION IF NOT EXISTS ...` lines
#     no-ops, so no superuser is required at replay time.
#
#     Idempotent: `CREATE EXTENSION IF NOT EXISTS` skips when present, so
#     this runs unconditionally — whether gitlabhq_development was created
#     in this invocation or already existed.
# ---------------------------------------------------------------------------

echo ""
echo "==> Mirroring gitlabhq_development extensions into template1..."

EXT_ROWS=$($KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
  env PGPASSWORD="$PG_PASS" psql -U postgres -d gitlabhq_development -tAF '|' -c \
    "SELECT e.extname, n.nspname \
     FROM pg_extension e \
     JOIN pg_namespace n ON e.extnamespace = n.oid \
     WHERE e.extname <> 'plpgsql' \
     ORDER BY e.extname" 2>/dev/null || true)

if [[ -z "$EXT_ROWS" ]]; then
  echo "  (no extensions to mirror)"
else
  while IFS='|' read -r ext schema; do
    [[ -z "$ext" ]] && continue
    if $KUBECTL exec -n "$NAMESPACE" "$PG_POD" -- \
      env PGPASSWORD="$PG_PASS" psql -U postgres -d template1 -c \
        "CREATE SCHEMA IF NOT EXISTS \"$schema\"; CREATE EXTENSION IF NOT EXISTS \"$ext\" WITH SCHEMA \"$schema\";" >/dev/null; then
      echo "  ✓ $ext (schema $schema)"
    else
      error "Failed to install extension '$ext' in template1."
      exit 1
    fi
  done <<< "$EXT_ROWS"
fi

echo ""
echo "==> Rewriting database names in config/database.yml..."
if [[ -f "$DB_YML" ]]; then
  sed -i.bak 's/database: gitlabhq_production/database: gitlabhq_development/g' "$DB_YML"
  rm "$DB_YML.bak"
  echo "  ✓ config/database.yml now references gitlabhq_development"
else
  warn "config/database.yml not found – skipping database name rewrite"
fi

# ---------------------------------------------------------------------------
# 5c. Add test: sections to YAML config files
#
#     RSpec requires a `test` environment.  For each config file that was
#     rewritten from production → development, append a `test:` block by
#     duplicating the `development:` section.  database.yml gets an extra
#     rewrite (gitlabhq_development → gitlabhq_test).
# ---------------------------------------------------------------------------

echo ""
echo "==> Adding test: sections to config files..."

TEST_SECTION_FILES=(
  "config/database.yml"
  "config/gitlab.yml"
  "config/cable.yml"
  "config/resque.yml"
  "config/redis.action_cable.yml"
  "config/session_store.yml"
  "config/secrets.yml"
)

for file in "${TEST_SECTION_FILES[@]}"; do
  file_path="$GITLAB_DIR/$file"
  if [[ ! -f "$file_path" ]]; then
    warn "$file not found – skipping test section"
    continue
  fi

  # Skip if test: section already exists
  if grep -q '^test:' "$file_path"; then
    echo "  ✓ $file already has a test: section – skipping"
    continue
  fi

  if [[ "$file" == "config/gitlab.yml" ]]; then
    # gitlab.yml: rewrite /srv/gitlab paths to local tmp/tests so tests
    # don't try to write to cluster-only paths, and rewrite gitaly_address
    # from tcp:// to a local unix socket for the test Gitaly process.
    {
      echo ""
      awk -v repo="$GITLAB_DIR" '
        BEGIN { gsub(/[&\\]/, "\\\\&", repo) }
        /^development:/{found=1; print "test:"; next}
        found && /^[^ ]/{exit}
        found{
          gsub(/\/srv\/gitlab/, repo "/tmp/tests")
          gsub(/\/home\/git/, repo "/tmp/tests")
          gsub(/gitaly_address: tcp:\/\/[^ ]+/, "gitaly_address: unix:" repo "/tmp/tests/gitaly/praefect.socket")
          gsub(/_development/, "_test")
          print
        }
      ' "$file_path"
    } >> "$file_path"
  else
    # Duplicate development: block as test:, rewriting *_development
    # identifiers to *_test so the test env uses its own database name
    # (gitlabhq_development → gitlabhq_test).  The same rule defensively
    # covers any future *_development identifier CNG may emit.
    {
      echo ""
      awk '/^development:/{found=1; print "test:"; next} found && /^[^ ]/{exit} found{gsub(/_development/, "_test"); print}' "$file_path"
    } >> "$file_path"
  fi
  echo "  ✓ $file"
done

# ---------------------------------------------------------------------------
# 5d. Enable pages.local_store only in the test: block of gitlab.yml
#
#     The cluster config has pages.local_store.enabled: false because prod
#     uses object storage. RSpec's TestEnv resolves pages_path via
#     Gitlab::Pages::Settings#path, which raises DiskAccessDenied unless
#     local_store is enabled. We flip it to true for test: only, leaving
#     development: matching cluster prod.
# ---------------------------------------------------------------------------

GITLAB_YML="$GITLAB_DIR/config/gitlab.yml"
if [[ -f "$GITLAB_YML" ]]; then
  echo ""
  echo "==> Enabling pages.local_store in the test: block of config/gitlab.yml..."
  awk '
    /^test:/                        { in_test = 1 }
    in_test && /^    local_store:$/ { print; getline; sub(/false/, "true"); print; next }
    { print }
  ' "$GITLAB_YML" > "$GITLAB_YML.tmp" && mv "$GITLAB_YML.tmp" "$GITLAB_YML"
  echo "  ✓ config/gitlab.yml"
fi

# ---------------------------------------------------------------------------
# 5e. Clear /etc/ paths in the test: block of gitlab.yml
#
#     The cluster config points various secret/key/keytab/ca_file settings
#     at /etc/gitlab/... or /etc/krb5.keytab, none of which exist on local
#     machines during tests.  Any setting whose value points under /etc/ is
#     blanked.  For features with sensible defaults (workhorse,
#     gitlab_shell) Rails falls back to the default file relative to
#     Rails.root.  For features that are disabled (kerberos, smartcard,
#     iam_auth_service, pages) the value is never read.  For enabled
#     features that lack a default (registry), specs stub the config.
# ---------------------------------------------------------------------------

if [[ -f "$GITLAB_YML" ]]; then
  echo ""
  echo "==> Clearing /etc/ paths in the test: block of config/gitlab.yml..."
  awk '
    /^test:/                             { in_test = 1 }
    in_test && /^[^ ]/ && !/^test:/      { in_test = 0 }
    in_test && /^ +[a-zA-Z_]+:[ ]+.*\/etc\// {
      sub(/:[ ]+.*/, ":")
      print
      next
    }
    { print }
  ' "$GITLAB_YML" > "$GITLAB_YML.tmp" && mv "$GITLAB_YML.tmp" "$GITLAB_YML"
  echo "  ✓ config/gitlab.yml"
fi

# ---------------------------------------------------------------------------
# 6. Write static vite.gdk.json
#
#    vite.gdk.json is committed to the repo and should always use 127.0.0.1
#    so that the Vite dev server is reachable via port-forward.  Writing it
#    here is a no-op in most cases but ensures correctness if the file was
#    regenerated or replaced (e.g. by gdk rake generate_config_files).
# ---------------------------------------------------------------------------

echo ""
echo "==> Writing static config/vite.gdk.json..."

cat > "$GITLAB_DIR/config/vite.gdk.json" <<'EOF'
{
  "enabled": true,
  "public_host": "127.0.0.1",
  "host": "127.0.0.1",
  "port": 3038,
  "hmr": {
    "clientPort": 3038,
    "host": "127.0.0.1",
    "protocol": "ws"
  }
}
EOF
echo "  ✓ config/vite.gdk.json"

# ---------------------------------------------------------------------------
# 7. Summary
# ---------------------------------------------------------------------------

echo ""
success "==> Setup complete."
success ""
success "  Copied: ${COPIED_FILES[*]:-none}"
[[ ${#FAILED_FILES[@]} -gt 0 ]] && success "  Skipped : ${FAILED_FILES[*]}"
success "  Rewritten to development env: ${MODIFIED_FILES[*]:-none}"
success "  Unable to modify files: ${UNMODIFIED_FILES[*]:-none}"
success ""
echo 'Next: Run `caproni run`'
