#!/bin/bash
set -e
BASEDIR="$(cd "`dirname $0`"; pwd)"
. "${BASEDIR}/colors-inc.sh"

BASEDIR=`pwd`

TARGET=/tmp/csr-$$
mkdir -p $TARGET
CONF=$TARGET/csr.conf

_cleanUp() { 
  rm -f "${CONF}"
  rmdir "${TARGET}"
}
trap _cleanUp EXIT

usage() {
  echo "${RED}Usage $0 -ca directory"
}

CA_DIR="ca"
EXP_PWD="changeit"

EXT_TO_USE="v3_req"

while true; do
  case $1 in
    -ca)
      shift
      CA_DIR="$1"
      shift
      ;;
    -*)
      echo "${RED}Unknown option $1!${ENDCOLOR}"
      usage
      exit 1
      ;;
    *)
      break;
      ;;
  esac
done

# Split args to local vars
X509_CN="Private Root CA"

X509_C="DE"
X509_ST="Hesse"
X509_L="Kassel"
X509_O="Elektrowolle"
X509_OU="Local CA"

# generate openssl config file
egrep -v '^OU =\s+$' >$CONF <<EOF
[req]
distinguished_name = req_distinguished_name
default_ca      = CA_default            # The default ca section
req_extensions = v3_req
prompt = no

[ ca ]
default_ca      = CA_default            # The default ca section

[ CA_default ]
dir            = ${CA_DIR}              # top dir
database       = \$dir/index.txt        # index file.
new_certs_dir  = \$dir/newcerts         # new certs dir

certificate    = \$dir/selfSignCA.crt   # The CA cert
# serial         = \$dir/selfSignCA.srl   # serial no file
private_key    = \$dir/selfSignCA.key   # CA private key
RANDFILE       = \$dir/.rand            # random number file

default_days   = 10000                  # how long to certify for
default_crl_days= 30                    # how long before next CRL
default_md     = sha256                 # md to use

policy         = policy_any            # default policy
email_in_dn    = no                    # Don't add the email into cert DN

name_opt       = ca_default            # Subject name display option
cert_opt       = ca_default            # Certificate display option
copy_extensions = none                 # Don't copy extensions from request
unique_subject = no

[ policy_any ]
countryName            = supplied
stateOrProvinceName    = supplied
organizationName       = supplied
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

[req_distinguished_name]
C = ${X509_C}
ST = ${X509_ST}
L = ${X509_L}
O = ${X509_O}
OU = ${X509_OU}
CN = ${X509_CN}

[v3_req]
keyUsage = critical, keyCertSign, digitalSignature
basicConstraints = critical, CA:TRUE

[alt_names]
EOF

mkdir -p "${CA_DIR}"

# Ready to do our work
echo "${YELLOW}Using config for selfSignCA:${ENDCOLOR}"
echo
cat "${CONF}"
echo
if [ -f "${CA_DIR}/selfSignCA.key" ]; then
  echo "${YELLOW}The selfSignCA.key file is already present, won't create new key file${ENDCOLOR}"
else 
  echo "${GREEN}Generate KEY${ENDCOLOR}"
  openssl genrsa -out "${CA_DIR}/selfSignCA.key" 4096
fi
echo "${GREEN}Generate CSR${ENDCOLOR}"
openssl req -new -utf8 -sha256 -key "${CA_DIR}/selfSignCA.key" -out "${CA_DIR}/selfSignCA.csr" -config "${CONF}"
openssl req -in "${CA_DIR}/selfSignCA.csr"

echo "${GREEN}Generate self-signed CA${ENDCOLOR}"
openssl x509 -req -sha256 -days 10000 -in "${CA_DIR}/selfSignCA.csr" -signkey "${CA_DIR}/selfSignCA.key" -out "${CA_DIR}/selfSignCA.crt" -extfile "${CONF}" -extensions ${EXT_TO_USE}
echo "${GREEN}pkcs#12 export password: ${EXP_PWD}${ENDCOLOR}"
openssl pkcs12 -passout "pass:${EXP_PWD}" -export -inkey "${CA_DIR}/selfSignCA.key" -in "${CA_DIR}/selfSignCA.crt" -out "${CA_DIR}/selfSignCA.p12"

openssl x509 -text -in "${CA_DIR}/selfSignCA.crt"

echo "${GREEN}Done!${ENDCOLOR}"

