#!/usr/bin/env bash
echo "Running LocalStack bootstrap script: 10-bootstrap.sh"

set -euo pipefail

REGION="${AWS_DEFAULT_REGION:-ca-central-1}"

# awslocal is the LocalStack wrapper so you don't need --endpoint-url
# (it targets the LocalStack gateway automatically)
# Docs: https://docs.localstack.cloud/.../aws-cli/
ensure_bucket() {
  local b="$1"
  if ! awslocal s3api head-bucket --bucket "$b" >/dev/null 2>&1; then
    awslocal s3api create-bucket \
      --bucket "$b" \
      --create-bucket-configuration LocationConstraint="$REGION" \
      --region "$REGION" >/dev/null
  fi
}

ensure_log_group() {
  local lg="$1"
  awslocal logs create-log-group --log-group-name "$lg" --region "$REGION" >/dev/null 2>&1 || true
}

ensure_secret_string() {
  local name="$1"
  local value="$2"

  if awslocal secretsmanager describe-secret --secret-id "$name" >/dev/null 2>&1; then
    awslocal secretsmanager update-secret --secret-id "$name" --secret-string "$value" >/dev/null
  else
    awslocal secretsmanager create-secret --name "$name" --secret-string "$value" >/dev/null
  fi
}

ensure_secret_file() {
  local name="$1"
  local filepath="$2"

  if awslocal secretsmanager describe-secret --secret-id "$name" >/dev/null 2>&1; then
    awslocal secretsmanager update-secret --secret-id "$name" --secret-string "file://$filepath" >/dev/null
  else
    awslocal secretsmanager create-secret --name "$name" --secret-string "file://$filepath" >/dev/null
  fi
}

# SES identities (idempotent-ish; ignoring if it already exists)
awslocal ses verify-domain-identity --domain imex.online --region "$REGION" >/dev/null || true
awslocal ses verify-email-identity --email-address noreply@imex.online --region "$REGION" >/dev/null || true

# Secrets
ensure_secret_file "CHATTER_PRIVATE_KEY" "/tmp/certs/io-ftp-test.key"
ensure_secret_string "CHATTER_COMPANY_KEY_6713" "${CHATTER_COMPANY_KEY_6713}"
ensure_secret_string "CHATTER_COMPANY_KEY_6746" "${CHATTER_COMPANY_KEY_6746}"

# Logs
ensure_log_group "development"

# Buckets
ensure_bucket "imex-job-totals"
ensure_bucket "parts-estimate"
ensure_bucket "imex-large-log"
ensure_bucket "imex-carfax-uploads"
ensure_bucket "rome-carfax-uploads"
ensure_bucket "rps-carfax-uploads"
