#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
TEMPLATE="$ROOT/.env.load.example"
ENV_FILE="$ROOT/.env.load"

for command in openssl perl; do
  if ! command -v "$command" >/dev/null 2>&1; then
    echo "Required command is unavailable: $command" >&2
    exit 1
  fi
done

if [ -f "$ENV_FILE" ]; then
  chmod 600 "$ENV_FILE"

  needs_fixture_password=true
  needs_oban_maintenance_concurrency=true
  needs_oban_push_concurrency=true
  needs_resilience_timeout=true
  needs_resilience_interval=true
  needs_resilience_request_timeout=true
  needs_traefik_retry_attempts=true
  needs_observability_prometheus_port=true
  needs_observability_alertmanager_port=true
  needs_observability_grafana_port=true
  needs_observability_scrape_interval=true
  needs_observability_evaluation_interval=true
  needs_observability_timeout=true
  needs_observability_grafana_user=true
  needs_observability_grafana_password=true
  needs_backup_minio_api_port=true
  needs_backup_minio_console_port=true
  needs_backup_minio_root_user=true
  needs_backup_minio_root_password=true
  needs_backup_restic_password=true
  needs_backup_bucket_prefix=true
  needs_backup_timeout=true
  needs_backup_interruption_chunks=true
  needs_backup_interruption_chunk_bytes=true
  needs_backup_interruption_interval=true

  grep -q '^LOAD_FIXTURE_PASSWORD=' "$ENV_FILE" && needs_fixture_password=false
  grep -q '^OBAN_MAINTENANCE_CONCURRENCY=' "$ENV_FILE" &&
    needs_oban_maintenance_concurrency=false
  grep -q '^OBAN_PUSH_CONCURRENCY=' "$ENV_FILE" &&
    needs_oban_push_concurrency=false
  grep -q '^LOAD_RESILIENCE_RECOVERY_TIMEOUT_SECONDS=' "$ENV_FILE" &&
    needs_resilience_timeout=false
  grep -q '^LOAD_RESILIENCE_PROBE_INTERVAL_SECONDS=' "$ENV_FILE" &&
    needs_resilience_interval=false
  grep -q '^LOAD_RESILIENCE_REQUEST_TIMEOUT_SECONDS=' "$ENV_FILE" &&
    needs_resilience_request_timeout=false
  grep -q '^TRAEFIK_RETRY_ATTEMPTS=' "$ENV_FILE" && needs_traefik_retry_attempts=false
  grep -q '^OBSERVABILITY_PROMETHEUS_PORT=' "$ENV_FILE" &&
    needs_observability_prometheus_port=false
  grep -q '^OBSERVABILITY_ALERTMANAGER_PORT=' "$ENV_FILE" &&
    needs_observability_alertmanager_port=false
  grep -q '^OBSERVABILITY_GRAFANA_PORT=' "$ENV_FILE" &&
    needs_observability_grafana_port=false
  grep -q '^OBSERVABILITY_SCRAPE_INTERVAL=' "$ENV_FILE" &&
    needs_observability_scrape_interval=false
  grep -q '^OBSERVABILITY_EVALUATION_INTERVAL=' "$ENV_FILE" &&
    needs_observability_evaluation_interval=false
  grep -q '^OBSERVABILITY_TIMEOUT_SECONDS=' "$ENV_FILE" &&
    needs_observability_timeout=false
  grep -q '^OBSERVABILITY_GRAFANA_ADMIN_USER=' "$ENV_FILE" &&
    needs_observability_grafana_user=false
  grep -q '^OBSERVABILITY_GRAFANA_ADMIN_PASSWORD=' "$ENV_FILE" &&
    needs_observability_grafana_password=false
  grep -q '^BACKUP_MINIO_API_PORT=' "$ENV_FILE" &&
    needs_backup_minio_api_port=false
  grep -q '^BACKUP_MINIO_CONSOLE_PORT=' "$ENV_FILE" &&
    needs_backup_minio_console_port=false
  grep -q '^BACKUP_MINIO_ROOT_USER=' "$ENV_FILE" &&
    needs_backup_minio_root_user=false
  grep -q '^BACKUP_MINIO_ROOT_PASSWORD=' "$ENV_FILE" &&
    needs_backup_minio_root_password=false
  grep -q '^BACKUP_RESTIC_PASSWORD=' "$ENV_FILE" &&
    needs_backup_restic_password=false
  grep -q '^BACKUP_BUCKET_PREFIX=' "$ENV_FILE" &&
    needs_backup_bucket_prefix=false
  grep -q '^BACKUP_TIMEOUT_SECONDS=' "$ENV_FILE" &&
    needs_backup_timeout=false
  grep -q '^BACKUP_INTERRUPTION_CHUNKS=' "$ENV_FILE" &&
    needs_backup_interruption_chunks=false
  grep -q '^BACKUP_INTERRUPTION_CHUNK_BYTES=' "$ENV_FILE" &&
    needs_backup_interruption_chunk_bytes=false
  grep -q '^BACKUP_INTERRUPTION_INTERVAL_SECONDS=' "$ENV_FILE" &&
    needs_backup_interruption_interval=false

  if [ "$needs_fixture_password" = false ] &&
    [ "$needs_oban_maintenance_concurrency" = false ] &&
    [ "$needs_oban_push_concurrency" = false ] &&
    [ "$needs_resilience_timeout" = false ] &&
    [ "$needs_resilience_interval" = false ] &&
    [ "$needs_resilience_request_timeout" = false ] &&
    [ "$needs_traefik_retry_attempts" = false ] &&
    [ "$needs_observability_prometheus_port" = false ] &&
    [ "$needs_observability_alertmanager_port" = false ] &&
    [ "$needs_observability_grafana_port" = false ] &&
    [ "$needs_observability_scrape_interval" = false ] &&
    [ "$needs_observability_evaluation_interval" = false ] &&
    [ "$needs_observability_timeout" = false ] &&
    [ "$needs_observability_grafana_user" = false ] &&
    [ "$needs_observability_grafana_password" = false ] &&
    [ "$needs_backup_minio_api_port" = false ] &&
    [ "$needs_backup_minio_console_port" = false ] &&
    [ "$needs_backup_minio_root_user" = false ] &&
    [ "$needs_backup_minio_root_password" = false ] &&
    [ "$needs_backup_restic_password" = false ] &&
    [ "$needs_backup_bucket_prefix" = false ] &&
    [ "$needs_backup_timeout" = false ] &&
    [ "$needs_backup_interruption_chunks" = false ] &&
    [ "$needs_backup_interruption_chunk_bytes" = false ] &&
    [ "$needs_backup_interruption_interval" = false ]; then
    echo ".env.load already exists; no secret or experiment input was changed."
    exit 0
  fi

  umask 077
  load_fixture_password=
  observability_grafana_admin_password=
  backup_minio_root_user=
  backup_minio_root_password=
  backup_restic_password=

  if [ "$needs_fixture_password" = true ]; then
    load_fixture_password=$(openssl rand -hex 24)
  fi

  if [ "$needs_observability_grafana_password" = true ]; then
    observability_grafana_admin_password=$(openssl rand -hex 32)
  fi

  if [ "$needs_backup_minio_root_user" = true ]; then
    backup_minio_root_user="wnh$(openssl rand -hex 12)"
  fi

  if [ "$needs_backup_minio_root_password" = true ]; then
    backup_minio_root_password=$(openssl rand -hex 32)
  fi

  if [ "$needs_backup_restic_password" = true ]; then
    backup_restic_password=$(openssl rand -hex 32)
  fi

  {
    if [ "$needs_fixture_password" = true ]; then
      printf '\n# Added by the authenticated-load profile upgrade.\n'
      printf 'LOAD_AUTH_VUS=8\n'
      printf 'LOAD_AUTH_WS_TIMEOUT_MS=5000\n'
      printf 'LOAD_AUTH_THINK_SECONDS=0.1\n'
      printf 'LOAD_FIXTURE_PASSWORD=%s\n' "$load_fixture_password"
    fi

    if [ "$needs_oban_maintenance_concurrency" = true ] ||
      [ "$needs_oban_push_concurrency" = true ]; then
      printf '\n# Added by the worker-queue configuration upgrade.\n'
    fi

    if [ "$needs_oban_maintenance_concurrency" = true ]; then
      printf 'OBAN_MAINTENANCE_CONCURRENCY=2\n'
    fi

    if [ "$needs_oban_push_concurrency" = true ]; then
      printf 'OBAN_PUSH_CONCURRENCY=1\n'
    fi

    if [ "$needs_resilience_timeout" = true ] ||
      [ "$needs_resilience_interval" = true ]; then
      printf '\n# Added by the local resilience-profile upgrade.\n'
    fi

    if [ "$needs_resilience_timeout" = true ]; then
      printf 'LOAD_RESILIENCE_RECOVERY_TIMEOUT_SECONDS=120\n'
    fi

    if [ "$needs_resilience_interval" = true ]; then
      printf 'LOAD_RESILIENCE_PROBE_INTERVAL_SECONDS=0.05\n'
    fi

    if [ "$needs_resilience_request_timeout" = true ]; then
      printf 'LOAD_RESILIENCE_REQUEST_TIMEOUT_SECONDS=2\n'
    fi

    if [ "$needs_traefik_retry_attempts" = true ]; then
      printf 'TRAEFIK_RETRY_ATTEMPTS=3\n'
    fi

    if [ "$needs_observability_prometheus_port" = true ] ||
      [ "$needs_observability_alertmanager_port" = true ] ||
      [ "$needs_observability_grafana_port" = true ] ||
      [ "$needs_observability_scrape_interval" = true ] ||
      [ "$needs_observability_evaluation_interval" = true ] ||
      [ "$needs_observability_timeout" = true ] ||
      [ "$needs_observability_grafana_user" = true ] ||
      [ "$needs_observability_grafana_password" = true ]; then
      printf '\n# Added by the local observability-profile upgrade.\n'
    fi

    if [ "$needs_observability_prometheus_port" = true ]; then
      printf 'OBSERVABILITY_PROMETHEUS_PORT=0\n'
    fi

    if [ "$needs_observability_alertmanager_port" = true ]; then
      printf 'OBSERVABILITY_ALERTMANAGER_PORT=0\n'
    fi

    if [ "$needs_observability_grafana_port" = true ]; then
      printf 'OBSERVABILITY_GRAFANA_PORT=0\n'
    fi

    if [ "$needs_observability_scrape_interval" = true ]; then
      printf 'OBSERVABILITY_SCRAPE_INTERVAL=1s\n'
    fi

    if [ "$needs_observability_evaluation_interval" = true ]; then
      printf 'OBSERVABILITY_EVALUATION_INTERVAL=1s\n'
    fi

    if [ "$needs_observability_timeout" = true ]; then
      printf 'OBSERVABILITY_TIMEOUT_SECONDS=90\n'
    fi

    if [ "$needs_observability_grafana_user" = true ]; then
      printf 'OBSERVABILITY_GRAFANA_ADMIN_USER=local-admin\n'
    fi

    if [ "$needs_observability_grafana_password" = true ]; then
      printf 'OBSERVABILITY_GRAFANA_ADMIN_PASSWORD=%s\n' \
        "$observability_grafana_admin_password"
    fi

    if [ "$needs_backup_minio_api_port" = true ] ||
      [ "$needs_backup_minio_console_port" = true ] ||
      [ "$needs_backup_minio_root_user" = true ] ||
      [ "$needs_backup_minio_root_password" = true ] ||
      [ "$needs_backup_restic_password" = true ] ||
      [ "$needs_backup_bucket_prefix" = true ] ||
      [ "$needs_backup_timeout" = true ] ||
      [ "$needs_backup_interruption_chunks" = true ] ||
      [ "$needs_backup_interruption_chunk_bytes" = true ] ||
      [ "$needs_backup_interruption_interval" = true ]; then
      printf '\n# Added by the encrypted local backup-profile upgrade.\n'
    fi

    if [ "$needs_backup_minio_api_port" = true ]; then
      printf 'BACKUP_MINIO_API_PORT=0\n'
    fi

    if [ "$needs_backup_minio_console_port" = true ]; then
      printf 'BACKUP_MINIO_CONSOLE_PORT=0\n'
    fi

    if [ "$needs_backup_minio_root_user" = true ]; then
      printf 'BACKUP_MINIO_ROOT_USER=%s\n' "$backup_minio_root_user"
    fi

    if [ "$needs_backup_minio_root_password" = true ]; then
      printf 'BACKUP_MINIO_ROOT_PASSWORD=%s\n' "$backup_minio_root_password"
    fi

    if [ "$needs_backup_restic_password" = true ]; then
      printf 'BACKUP_RESTIC_PASSWORD=%s\n' "$backup_restic_password"
    fi

    if [ "$needs_backup_bucket_prefix" = true ]; then
      printf 'BACKUP_BUCKET_PREFIX=wnh-backup\n'
    fi

    if [ "$needs_backup_timeout" = true ]; then
      printf 'BACKUP_TIMEOUT_SECONDS=120\n'
    fi

    if [ "$needs_backup_interruption_chunks" = true ]; then
      printf 'BACKUP_INTERRUPTION_CHUNKS=300\n'
    fi

    if [ "$needs_backup_interruption_chunk_bytes" = true ]; then
      printf 'BACKUP_INTERRUPTION_CHUNK_BYTES=1048576\n'
    fi

    if [ "$needs_backup_interruption_interval" = true ]; then
      printf 'BACKUP_INTERRUPTION_INTERVAL_SECONDS=0.1\n'
    fi
  } >>"$ENV_FILE"
  chmod 600 "$ENV_FILE"
  unset load_fixture_password observability_grafana_admin_password \
    backup_minio_root_user backup_minio_root_password backup_restic_password \
    needs_fixture_password needs_oban_maintenance_concurrency \
    needs_oban_push_concurrency needs_resilience_timeout \
    needs_resilience_interval needs_resilience_request_timeout \
    needs_traefik_retry_attempts needs_observability_prometheus_port \
    needs_observability_alertmanager_port needs_observability_grafana_port \
    needs_observability_scrape_interval needs_observability_evaluation_interval \
    needs_observability_timeout needs_observability_grafana_user \
    needs_observability_grafana_password needs_backup_minio_api_port \
    needs_backup_minio_console_port needs_backup_minio_root_user \
    needs_backup_minio_root_password needs_backup_restic_password \
    needs_backup_bucket_prefix needs_backup_timeout \
    needs_backup_interruption_chunks needs_backup_interruption_chunk_bytes \
    needs_backup_interruption_interval
  echo "Added missing queue/load/resilience/observability/backup inputs to ignored .env.load."
  exit 0
fi

if [ ! -f "$TEMPLATE" ]; then
  echo "Missing tracked template: $TEMPLATE" >&2
  exit 1
fi

umask 077
postgres_password=$(openssl rand -hex 32)
secret_key_base=$(openssl rand -hex 64)
handover_secret=$(openssl rand -hex 64)
release_cookie=$(openssl rand -hex 64)
metrics_token=$(openssl rand -hex 32)
load_fixture_password=$(openssl rand -hex 24)
observability_grafana_admin_password=$(openssl rand -hex 32)
backup_minio_root_user="wnh$(openssl rand -hex 12)"
backup_minio_root_password=$(openssl rand -hex 32)
backup_restic_password=$(openssl rand -hex 32)
database_url="ecto://wnh_load:${postgres_password}@db/who_need_help_load"
docker_socket_gid=$(stat -c '%g' /var/run/docker.sock)
temporary=$(mktemp "${ENV_FILE}.XXXXXX")
trap 'rm -f "$temporary"' EXIT HUP INT TERM

POSTGRES_PASSWORD_VALUE=$postgres_password \
DATABASE_URL_VALUE=$database_url \
SECRET_KEY_BASE_VALUE=$secret_key_base \
HANDOVER_SECRET_VALUE=$handover_secret \
RELEASE_COOKIE_VALUE=$release_cookie \
METRICS_TOKEN_VALUE=$metrics_token \
LOAD_FIXTURE_PASSWORD_VALUE=$load_fixture_password \
OBSERVABILITY_GRAFANA_ADMIN_PASSWORD_VALUE=$observability_grafana_admin_password \
BACKUP_MINIO_ROOT_USER_VALUE=$backup_minio_root_user \
BACKUP_MINIO_ROOT_PASSWORD_VALUE=$backup_minio_root_password \
BACKUP_RESTIC_PASSWORD_VALUE=$backup_restic_password \
DOCKER_SOCKET_GID_VALUE=$docker_socket_gid \
  perl -0pe '
    s/GENERATE_POSTGRES_PASSWORD/$ENV{POSTGRES_PASSWORD_VALUE}/g;
    s/GENERATE_DATABASE_URL/$ENV{DATABASE_URL_VALUE}/g;
    s/GENERATE_SECRET_KEY_BASE/$ENV{SECRET_KEY_BASE_VALUE}/g;
    s/GENERATE_HANDOVER_SECRET/$ENV{HANDOVER_SECRET_VALUE}/g;
    s/GENERATE_RELEASE_COOKIE/$ENV{RELEASE_COOKIE_VALUE}/g;
    s/GENERATE_METRICS_TOKEN/$ENV{METRICS_TOKEN_VALUE}/g;
    s/GENERATE_LOAD_FIXTURE_PASSWORD/$ENV{LOAD_FIXTURE_PASSWORD_VALUE}/g;
    s/GENERATE_OBSERVABILITY_GRAFANA_ADMIN_PASSWORD/$ENV{OBSERVABILITY_GRAFANA_ADMIN_PASSWORD_VALUE}/g;
    s/GENERATE_BACKUP_MINIO_ROOT_USER/$ENV{BACKUP_MINIO_ROOT_USER_VALUE}/g;
    s/GENERATE_BACKUP_MINIO_ROOT_PASSWORD/$ENV{BACKUP_MINIO_ROOT_PASSWORD_VALUE}/g;
    s/GENERATE_BACKUP_RESTIC_PASSWORD/$ENV{BACKUP_RESTIC_PASSWORD_VALUE}/g;
    s/REPLACE_WITH_DOCKER_SOCKET_NUMERIC_GID/$ENV{DOCKER_SOCKET_GID_VALUE}/g;
  ' "$TEMPLATE" >"$temporary"

if grep -Eq '^[A-Z0-9_]+=GENERATE_' "$temporary"; then
  echo "A secret marker was not replaced; refusing to publish .env.load." >&2
  exit 1
fi

chmod 600 "$temporary"
mv "$temporary" "$ENV_FILE"
trap - EXIT HUP INT TERM
unset postgres_password secret_key_base handover_secret release_cookie metrics_token \
  load_fixture_password observability_grafana_admin_password \
  backup_minio_root_user backup_minio_root_password backup_restic_password \
  database_url

echo "Generated independent load-profile secrets in ignored .env.load."
