#!/usr/bin/env bash
#
# Pull Caddy's internal root CA certificate off the running container host.
#
# With `proxy.tls: internal` Caddy runs its own CA, which means nothing trusts its
# certificate until you install that root. This fetches it so you can.
#
#   tools/export-proxy-ca.sh                 # from the local Docker daemon
#   tools/export-proxy-ca.sh <user@host>     # over SSH, from the container host
#
# The CA does not exist until Caddy has started at least once — there is nothing to
# export from a machine that has never run it, which is also why this can't be baked
# into an ISO at build time.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/coreconfig.sh
source "${SCRIPT_DIR}/lib/coreconfig.sh"

REMOTE="${1:-}"
# Caddy's documented location for the local CA's root inside its data directory.
CA_PATH="/data/caddy/pki/authorities/local/root.crt"
DEST_DIR="${CORE_REPO_ROOT}/proxy/ca"
DEST="${DEST_DIR}/root.crt"

mkdir -p "$DEST_DIR"

if [[ -n "$REMOTE" ]]; then
  core_log "Fetching the root CA from ${REMOTE}"
  ssh "$REMOTE" "sudo docker exec caddy cat ${CA_PATH}" > "$DEST"
else
  core_log "Fetching the root CA from the local Docker daemon"
  docker exec caddy cat "$CA_PATH" > "$DEST"
fi

if [[ ! -s "$DEST" ]]; then
  rm -f "$DEST"
  core_die "Got an empty certificate.
     Has the proxy started at least once? The CA is created on first run:
         docker logs caddy
     If you are running this from a different machine, pass the host:
         $0 user@container-host"
fi

core_log "Wrote ${DEST}"
cat <<EOF

  Install it where you need HTTPS without a warning:

    Debian/Ubuntu (system-wide):
        sudo cp ${DEST} /usr/local/share/ca-certificates/smarthome-root.crt
        sudo update-ca-certificates

    Firefox:  Settings -> Privacy & Security -> Certificates -> View Certificates
              -> Authorities -> Import (Firefox keeps its own store, so the system
              install above does NOT cover it)

    Chromium: Settings -> Privacy and security -> Security -> Manage certificates
              -> Authorities -> Import (its own NSS store, same caveat)

    Android:  Settings -> Security -> Encryption & credentials -> Install a certificate
              -> CA certificate

  This file is a public certificate, not a secret — but it IS gitignored, because a
  root CA your machines trust is not something to publish casually either.
EOF
