#!/usr/bin/env bash

OUTPUT_DIR=/etc/nginx/certs
CA_DIR=/etc/nginx/ca

mkdir -p "$OUTPUT_DIR" "$CA_DIR"

printf "\n%s\n"  "###Create rootRA.key"
openssl genrsa \
    -out "${CA_DIR}/rootCA.key" \
    2048 > /dev/null || exit 1

printf "\n%s\n"  "### Create rootCA.pem"
openssl req \
    -x509 \
    -new \
    -nodes \
    -subj '/CN=Development/O=Development/C=US' \
    -key "${CA_DIR}/rootCA.key" \
    -sha256 \
    -days 3650 \
    -out "${CA_DIR}/rootCA.pem" || exit 1

printf "\n%s\n" "### Create csr.pem"
openssl req \
    -x509 \
    -new \
    -nodes \
    -subj '/CN=Development/O=Development/C=US' \
    -key "${CA_DIR}/rootCA.key" \
    -sha256 \
    -days 3650 \
    -out "${OUTPUT_DIR}/csr.pem" || exit 1

printf "\n%s\n" "### Create https-proxy.csr"
openssl req \
    -new \
    -sha256 \
    -nodes \
    -newkey rsa:2048 \
    -keyout "${OUTPUT_DIR}/https-proxy.key" \
    -out "${OUTPUT_DIR}/https-proxy.csr" \
    -config /tmp/openssl.cnf > /dev/null || exit 1

printf "\n%s\n"  "###Create https-proxy.crt"
openssl x509 \
    -req \
    -in "${OUTPUT_DIR}/https-proxy.csr" \
    -CA "${CA_DIR}/rootCA.pem" \
    -CAkey "${CA_DIR}/rootCA.key" \
    -CAcreateserial \
    -out "${OUTPUT_DIR}/https-proxy.crt" \
    -sha256 \
    -days 3650 \
    -extfile /tmp/openssl.cnf \
    -extensions v3_ca || exit 1
