#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SECRETS_DIR="${ROOT_DIR}/secrets"
CERT_PATH="${SECRETS_DIR}/dev-proxy-cert.pem"
KEY_PATH="${SECRETS_DIR}/dev-proxy-key.pem"
HOSTNAME="${APP_HOST:-kif.local.ascorrea.com}"

mkdir -p "${SECRETS_DIR}"

if ! command -v mkcert >/dev/null 2>&1; then
  cat <<'EOF'
mkcert is required to generate local development certificates.

Install it first, then rerun this script.
Examples:
  brew install mkcert
  mkcert -install
EOF
  exit 1
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

TMP_CERT="${TMP_DIR}/${HOSTNAME}.pem"
TMP_KEY="${TMP_DIR}/${HOSTNAME}-key.pem"

mkcert -cert-file "${TMP_CERT}" -key-file "${TMP_KEY}" "${HOSTNAME}"

cp "${TMP_CERT}" "${CERT_PATH}"
cp "${TMP_KEY}" "${KEY_PATH}"

cat <<EOF
Created local TLS files:
  ${CERT_PATH}
  ${KEY_PATH}

You can now start the stack with:
  docker compose up --build
EOF
