#!/bin/bash

set -e

unset BUNDLE_PATH BUNDLE_WITHOUT

if [[ "${WITH_LOAD_BALANCER}" == "true" ]]; then
  gdk config set postgresql.replica.enabled true
  gdk config set postgresql.replica_2.enabled true
  gdk config set load_balancing.enabled true
  gdk reconfigure
fi

if [[ "${QA_GITALY_TRANSACTIONS_ENABLED}" == "true" ]]; then
  gdk config set gitaly.transactions.enabled true
  gdk config set praefect.enabled false
  gdk reconfigure
fi

if [[ "${WITH_SECRETS_MANAGER}" == "true" ]]; then
  gdk config set openbao.enabled true
  gdk reconfigure
fi

# Split logs in to multiple files when running in CI
if [ -z "$CI" ]; then
  gdk start

  exec "$@" | tee -a ${HOME}/gitlab-development-kit/gitlab/log/gdk-container.log
else
  logs=("gitaly" "gitlab-workhorse" "postgresql" "rails-background-jobs" "redis" "sshd" "vite" "rails-web" "sidekiq-cron" "webpack" "gitlab-http-router" "gitlab-topology-service" "openbao")
  for log in "${logs[@]}"; do
    gdk tail $log &>${CI_BUILDS_DIR}/gdk.${log}.log &
  done

  # TODO: Check if we can reconfigure gitlab to write logs directly to `BUILDS_DIR`
  for logfile in ${HOME}/gitlab-development-kit/gitlab/log/*.log; do
    tail -f "$logfile" &>"${CI_BUILDS_DIR}"/$(basename "$logfile") &
  done

  # Set the host IP as a trusted proxy, because we can be running
  # HTTP router on the same host, which is acting as a reverse proxy,
  # and if we're not trusting it it would be considered the client IP,
  # which will be wrong. See:
  # https://gitlab.com/gitlab-org/gitlab/-/issues/499657
  HOST_IP=$(getent hosts gdk.test | cut -d' ' -f1)
  ruby -ryaml -e "
    config_file = '${HOME}/gitlab-development-kit/gitlab/config/gitlab.yml'
    config = YAML.load_file(config_file, aliases: true)
    (config['development']['gitlab']['trusted_proxies'] ||= []) << '${HOST_IP}'
    File.write(config_file, YAML.dump(config))
  "

  gdk start

  exec "$@"
fi
