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

READ_NODE_CONF=\
$(cat << END
from pulp_node.config import read_config
node_conf = read_config()
print node_conf.main.node_certificate
END
)

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


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

mkdir -p `dirname $NODE_CRT`

# create client key
OLD_UMASK="$(umask)"
umask 0027
openssl genrsa -out $NODE_CRT 4096 &> /dev/null
chgrp apache $NODE_CRT
umask $OLD_UMASK

# create signing request for client
openssl req \
  -new \
  -key $NODE_CRT \
  -out $TMP/$BASE.req \
  -subj "/CN=$CN/O=$ORG/OU=$ORG_UNIT" &> /dev/null

# sign server request w/ CA key and gen x.509 cert.
openssl x509 \
  -req  \
  -in $TMP/$BASE.req \
  -out $TMP/$BASE.crt \
  -sha1 \
  -CA $CA_CRT \
  -CAkey $CA_KEY \
  -CAcreateserial \
  -set_serial $RANDOM \
  -days 3650 &> /dev/null

# bundle
cat $TMP/$BASE.crt >> $NODE_CRT

# clean
rm $TMP/$BASE.req
rm $TMP/$BASE.crt
rmdir $TMP
