#!/bin/bash
set -e # stop and exit on any error

PROJECT_DOMAIN="code-dev.g4dge7.com"
PROJECT_NAME="Gadget Code"

WITH_INSTALL=1

for arg in "$@"; do
  if [ "$arg" == "--without-install" ]; then
    WITH_INSTALL=0
  fi
done

# Clean up old files
rm -f *crt *key

#
# ROOT CA
#

# Generate Root CA private key
echo "Generating Root CA..."
openssl genrsa -des3 -out ${PROJECT_DOMAIN}.rootCA.key 2048

# Create Root CA self-signed certificate
openssl req -x509 \
  -new -nodes -key ${PROJECT_DOMAIN}.rootCA.key \
  -sha256 -days 1024 \
  -out ${PROJECT_DOMAIN}.rootCA.crt \
  -subj "/C=US/ST=Pennsylvania/L=Pittsburgh/O=DTP Technologies, LLC/CN=${PROJECT_NAME} Root CA"

#
# DEVELOPMENT CERTIFICATE
#

# Create an OpenSSL configuration file for the development certificate
echo "Creating OpenSSL configuration file for development certificate..."
cat > ${PROJECT_DOMAIN}.cnf <<EOF
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
C = US
ST = Pennsylvania
L = Pittsburgh
O = DTP Technologies, LLC
CN = ${PROJECT_DOMAIN} # The Common Name (CN) is for backwards compatibility.

[v3_req]
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = ${PROJECT_DOMAIN}
DNS.2 = localhost
EOF

# Generate Development Certificate private key
echo "Generating development certificate private key..."
openssl genrsa -out ${PROJECT_DOMAIN}.key 2048

# Create CSR using the configuration file
echo "Generating development certificate signing request with Root CA..."
openssl req -new \
  -key ${PROJECT_DOMAIN}.key \
  -out ${PROJECT_DOMAIN}.csr \
  -config ${PROJECT_DOMAIN}.cnf

# Sign the CSR with Root CA
echo "Signing development certificate with Root CA..."
openssl x509 -req \
  -days 3650 \
  -in ${PROJECT_DOMAIN}.csr \
  -CA ${PROJECT_DOMAIN}.rootCA.crt \
  -CAkey ${PROJECT_DOMAIN}.rootCA.key \
  -CAcreateserial \
  -out ${PROJECT_DOMAIN}.crt \
  -extfile ${PROJECT_DOMAIN}.cnf \
  -extensions v3_req

#
# Install to NSS db for Chromium and others
#

if [ $WITH_INSTALL == 1 ]; then
  ./install-certs
fi

#
# Clean up
#

echo "Done."