#!/bin/bash

COMMON_NAME="ca-cert"
SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME"
NUM_OF_DAYS=10000

argc=$#
argv=("$@")

if [ -z "$1" ]
then
  echo "Не указаны ip-адреса для сертификата";
  exit;
else
cat << EOF > v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
EOF

for (( j=0; j<argc; j++ )); do
    echo "IP.$((j+1))=${argv[j]}" >> v3.ext
done
fi

# private key 
openssl genrsa -out rootCA.key 2048

# cert
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -subj "$SUBJECT" -out rootCA.pem

if [ -f device.key ]; then
  KEY_OPT="-key"
else
  KEY_OPT="-keyout"
fi

openssl req -newkey rsa:2048 -days $NUM_OF_DAYS -nodes -keyout device.key -subj "$SUBJECT" > device.csr

cat v3.ext | sed s/%%DOMAIN%%/$COMMON_NAME/g > /tmp/__v3.ext

openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days $NUM_OF_DAYS -sha256 -extfile /tmp/__v3.ext

mv device.csr $COMMON_NAME.csr
cp device.crt $COMMON_NAME.crt

# remove temp file
rm -f device.crt;

