#!/bin/bash

if [ $# -lt 1 ]; then
   echo Usage: $(basename $0) [template]
   exit
fi

template=$1
tmpdir=$(mktemp -d)
outfile=$tmpdir/oc_appliance.cnf
filebasename=oc_appliance
filebasepath=$tmpdir/self_signed

cat $template > $outfile
echo DNS.1=$(hostname --fqdn) >> $outfile
declare i=0
for ip in $(ip r | grep src | cut -d' ' -f12); do
i=$((i+1))
echo IP.i=$ip >> $outfile
done;

# Generate key
openssl genrsa -out ${filebasepath}.key 2048

# Generate CSR
openssl req -new -out ${filebasepath}.csr \
                 -key ${filebasepath}.key \
                 -config $tmpdir/oc_appliance.cnf \
                 -sha256 -batch

# Sign CSR, creates cert
openssl x509 -req -days $((365*3)) \
                  -in ${filebasepath}.csr \
                  -signkey ${filebasepath}.key \
                  -out ${filebasepath}.crt \
                  -extensions v3_req \
                  -extfile $tmpdir/oc_appliance.cnf \

sudo install -m 600 -o root $filebasepath.key /etc/ssl/private
sudo install -m 644 -o root $filebasepath.crt /etc/ssl/certs

rm -rf $tmpdir
