#!/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.
#

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=/tmp/$RANDOM
CA_KEY=${PULP_CONF[0]}
CA_CRT=${PULP_CONF[1]}
CN=`hostname`
ORG="PULP"

mkdir -p $TMP

# create CA key
openssl genrsa -out $TMP/ca.key 2048 &> /dev/null

# create signing request
openssl req \
  -new \
  -key $TMP/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 $TMP/ca.key \
  -in $TMP/ca.req \
  -out $TMP/ca.crt &> /dev/null

# install
cp $TMP/ca.key $CA_KEY
cp $TMP/ca.crt $CA_CRT
chown root:apache $CA_KEY
chown root:apache $CA_CRT
chmod 640 $CA_KEY
chmod 640 $CA_CRT

# clean
rm -rf $TMP