#!/bin/sh
# Prepares Pebble's own HTTPS listener before the service starts.
#
# This key pair is *not* the CA. It is the certificate Pebble presents on
# 127.0.0.1:14000 and :15000, and it never leaves the machine: nginx terminates
# the public TLS for acme-test.corecp.dev with a Let's Encrypt certificate and
# proxies to loopback, so no client anywhere has to trust this file. It is
# generated once and kept, because regenerating it on every start would be a
# second rotating thing for no gain.
set -e

STATE=/var/lib/corecp-pebble
CRT="$STATE/wfe.crt"
KEY="$STATE/wfe.key"

install -d -m 0750 "$STATE"

if [ -s "$CRT" ] && [ -s "$KEY" ]; then
    exit 0
fi

umask 077
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
    -keyout "$KEY" -out "$CRT" -days 3650 \
    -subj "/CN=corecp-pebble" \
    -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1" >/dev/null 2>&1

chmod 0640 "$CRT" "$KEY"
echo "corecp-pebble: generated the loopback listener certificate in $STATE"
