#!/usr/bin/bash
# SPDX-License-Identifier: MIT

die() {
  echo "${1}" >&2
  exit 1
}

SB_DSTDIR="${1:-.}"

mkdir -p "${SB_DSTDIR}"

# Platform key.
PK_KEY="${SB_DSTDIR}/PK.key"
PK_CRT="${SB_DSTDIR}/PK.crt"

# Key exchange key.
KEK_KEY="${SB_DSTDIR}/KEK.key"
KEK_CRT="${SB_DSTDIR}/KEK.crt"

[ -e "${PK_KEY}" ] && die "Platform Key (${PK_KEY}) already exists; exiting"
[ -e "${PK_CRT}" ] && die "Platform Key certificate (${PK_CRT}) already exists; exiting"
openssl req -new -x509 -newkey rsa:2048 -subj "/O=10mt/CN=10mt PK/" \
  -keyout "${PK_KEY}" -out "${PK_CRT}" -days 3650 -nodes -sha256

[ -e "${KEK_KEY}" ] && die "Key Exchange Key (${KEK_KEY}) already exists; exiting"
[ -e "${KEK_CRT}" ] && die "Key Exchange Key certificate (${KEK_CRT}) already exists; exiting"
# Create KEK private key
openssl genrsa -out "${KEK_KEY}" 2048
# Create KEK certificate signing request
openssl req -new -key "${KEK_KEY}" -out "${SB_DSTDIR}/KEK.csr" -subj "/O=10mt/CN=10mt KEK/"
# Sign KEK certificate with PK
openssl x509 -req -in "${SB_DSTDIR}/KEK.csr" -CA "${PK_CRT}" -CAkey "${PK_KEY}" \
  -CAcreateserial -out "${KEK_CRT}" -days 3650 -sha256
# Clean up CSR
rm "${SB_DSTDIR}/KEK.csr"
