#!/bin/bash
mkdir /tmp/certgen 2>/dev/null
cd /tmp/certgen

openssl genrsa -aes256 -out ca-key.pem -passout pass:"foobarpwd" 4096
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem -subj "/C=SK/ST=Slovakia/L=SK/O=sectorq.cloud/OU=IT/CN=sectorq.cloud" -passin pass:"foobarpwd"
openssl genrsa -out server-key.pem 4096
if [[ `hostname` == "nas" ]]
then
IP=`ip route get 8.8.8.8 | head -1 | cut -d' ' -f8`
else
IP=`ip route get 8.8.8.8 | head -1 | cut -d' ' -f7`
fi
HOST=`uname -n`
openssl req -subj "/CN=$HOST" -sha256 -new -key server-key.pem -out server.csr
echo subjectAltName = DNS:$HOST,DNS:${HOST}.home.lan,IP:$IP,IP:127.0.0.1 >> extfile.cnf
echo extendedKeyUsage = serverAuth >> extfile.cnf
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out server-cert.pem -extfile extfile.cnf -passin pass:"foobarpwd"
openssl genrsa -out key.pem 4096
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile-client.cnf
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out cert.pem -extfile extfile-client.cnf  -passin pass:"foobarpwd"
rm -v client.csr server.csr extfile.cnf extfile-client.cnf
chmod -v 0400 ca-key.pem key.pem server-key.pem
chmod -v 0444 ca.pem server-cert.pem cert.pem