#!/bin/bash
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
set -xe

# The files generated by this script are used in unit tests that create TLS
# connections between a localhost server and client. Run this script if any
# certificates used for tests are expired.

# Files generated by this script:
# server.rsa - private RSA server key
# server.pem - certificate chain containing certificates [server, intermediate, CA]

# generate the root CA certificate and key
openssl req -nodes \
          -x509 \
          -days 3650 \
          -newkey rsa:4096 \
          -keyout ca.key \
          -out ca.cert \
          -sha256 \
          -batch \
          -subj "/CN=SDK RSA CA"

# generate intermediate authority cert and key
openssl req -nodes \
          -newkey rsa:3072 \
          -keyout inter.key \
          -out inter.req \
          -sha256 \
          -batch \
          -subj "/CN=SDK RSA level 2 intermediate"

# generate key and signing request for server
openssl req -nodes \
          -newkey rsa:2048 \
          -keyout server.key \
          -out server.req \
          -sha256 \
          -batch \
          -subj "/CN=sdktest.com"

openssl rsa \
          -in server.key \
          -out server.rsa

# sign intermediate cert with CA root
openssl x509 -req \
            -in inter.req \
            -out inter.cert \
            -CA ca.cert \
            -CAkey ca.key \
            -sha256 \
            -days 3650 \
            -set_serial 123 \
            -extensions v3_inter -extfile openssl.cnf

# sign server cert with intermediate
openssl x509 -req \
            -in server.req \
            -out server.cert \
            -CA inter.cert \
            -CAkey inter.key \
            -sha256 \
            -days 2000 \
            -set_serial 456 \
            -extensions v3_end -extfile openssl.cnf

cat server.cert inter.cert ca.cert > server.pem
rm *.key *.cert *.req
