#!/bin/bash
#
# Generate the Pulp CA private key and certificate.
# They are generated only when both do not already exist.
#

set -e

READ_PULP_CONF=\
$(cat << END
from pulp.server.config import config as pulp_conf
print pulp_conf.get('security', 'cakey')
print pulp_conf.get('security', 'cacert')
END
)

PULP_CONF=(`python -c "$READ_PULP_CONF"`)

TMP="$(mktemp -d)"
CA_KEY=${PULP_CONF[0]}
CA_CRT=${PULP_CONF[1]}
CN=`hostname --fqdn`
ORG="PULP"

if [ -f ${CA_KEY} ] && [ -f ${CA_CRT} ]
then
  echo "Both ${CA_KEY} and ${CA_CRT} already exist."
  echo "Nothing generated."
  exit 0
fi

umask 027

# create CA key
openssl genrsa -out ${CA_KEY} 4096 &> /dev/null
chgrp apache ${CA_KEY}

# create signing request
openssl req \
  -new \
  -key ${CA_KEY} \
  -out ${TMP}/ca.req \
  -subj "/CN=$CN/O=$ORG" &> /dev/null

# create a self-signed CA certificate
openssl x509 \
  -req \
  -days 7035 \
  -sha1 \
  -extensions ca  \
  -signkey ${CA_KEY} \
  -in ${TMP}/ca.req \
  -out ${CA_CRT} &> /dev/null
chgrp apache ${CA_CRT}

# clean
rm ${TMP}/ca.req
rmdir ${TMP}

echo "Created: ${CA_KEY} and ${CA_CRT}"
