#!/usr/bin/env bash
set -e

echo -e "\033[36mCreate\033[39m: self-signed certificates"

CERTS_DIR=certs/live/xai-corp.net

function make_cert() {
mkdir -p $CERTS_DIR

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -batch \
  -keyout $CERTS_DIR/privkey.pem \
  -out $CERTS_DIR/fullchain.pem \
  -config certs/xai-corp.net.conf

#tell chrome to trust the cert
  certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n "www.xai-corp.net" -i $CERTS_DIR/fullchain.pem
}

function test_cert() {
  ls -l $CERTS_DIR | grep privkey.pem
  ls -l $CERTS_DIR | grep fullchain.pem
}

function trap_exit() {
  code=$?
  if [ $code -gt 0 ]; then
    echo
    echo -e "\033[31mFailed to create certificates\033[39m"
    exit $code
  fi
}
trap  trap_exit EXIT

# RUN
make_cert && test_cert
