#!/bin/bash

# $1 is the first script argument, that will be the certificate's name.
# Other arguments are other domain names to be added to the certificate.

# Generate secret key
openssl req -new -nodes -out certs/$1.csr -newkey rsa:2048 -keyout certs/$1.key -subj "/CN=$1/C=AT/ST=Vienna/L=Vienna/O=MyOrg"

# Write certificate information
cat > certs/$1.v3.ext << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
EOF

# Iterate script arguments
let i=1
for name in "$@"
do
	echo "DNS.$i = $name" >> certs/$1.v3.ext
	let i++
	echo "DNS.$i = $name.localhost" >> certs/$1.v3.ext
	let i++
done

# Sign certificate with CA
openssl x509 -req -in certs/$1.csr -CA certs/ca.crt -CAkey certs/ca.key -CAcreateserial -out certs/$1.crt -days 730 -sha256 -extfile certs/$1.v3.ext -passin pass:foo
