#!/bin/bash
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
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"`)

# This temporary folder will contain the certificate signing request.
TMP="$(mktemp -d)"
CA_KEY=${PULP_CONF[0]}
CA_CRT=${PULP_CONF[1]}
CN=`hostname --fqdn`
ORG="PULP"

OLD_UMASK="$(umask)"
umask 027
# create CA key
openssl genrsa -out $CA_KEY 4096 &> /dev/null
# Allow httpd to read the key
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
umask $OLD_UMASK

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