#!/bin/bash
################################################################################
# Copyright (c) 2016 VMware, Inc. All rights reserved.
################################################################################
# Wrapper script aimed at refreshing SSL certificates on a vCenter server
# for PostgreSQL.

if [ -z $VMWARE_POSTGRES_BASE ]; then
   echo "VMWARE_POSTGRES_BASE is not set."
   echo "Check your installation."
   exit 1
fi
SANITY_FILE=$VMWARE_POSTGRES_BASE/scripts/vpostgres_sanity_checks
if [ -f $SANITY_FILE ]; then
   source $SANITY_FILE
else
   echo "Sanity check file for environment variables of VMware Postgres"
   echo "is not available. Check your installation."
   exit 1
fi

if [ -z $VMWARE_CIS_HOME ]; then
   echo "VMWARE_CIS_HOME is not set."
   echo "Check your installation."
   exit 1
fi

# Show utility help
show_help()
{
   ERROR_NUM=$1
   echo "Usage: `basename $0`"
   echo "Example: `basename $0`"
   exit $ERROR_NUM
}

EXPECTED_ARGS=0
if [ $# -ne $EXPECTED_ARGS ]; then
   # Leave with an error code
   show_help 1
fi

# Request certificates from vecs via its client and update the certificates.
# Those have been created at firstboot with the correct permissions, so
# overwriting them is not an issue even with --output that truncates the
# old file before writing it. If this command fails, it is likely that
# the set of certificates is not available, hence rely on the next restart
# done on the PostgreSQL server to check if something unexpected is going
# on. Do not do any validity checks here for simplicity.
CERT_FILE=${VMWARE_POSTGRES_DATA}/server.crt
KEY_FILE=${VMWARE_POSTGRES_DATA}/server.key
${VMWARE_CIS_HOME}/vmware-vmafd/bin/vecs-cli entry getkey \
      --store MACHINE_SSL_CERT  --alias __MACHINE_CERT \
      --output ${KEY_FILE}
ERRNUM=$?
if [ "$ERRNUM" != 0 ]; then
   echo "Could not generate SSL key file ${KEY_FILE}"
   exit 1
fi

${VMWARE_CIS_HOME}/vmware-vmafd/bin/vecs-cli entry getcert \
      --store MACHINE_SSL_CERT --alias __MACHINE_CERT \
      --output ${CERT_FILE}
ERRNUM=$?
if [ "$ERRNUM" != 0 ]; then
   echo "Could not generate SSL certificate file ${CERT_FILE}"
   exit 1
fi

chmod 600 ${KEY_FILE} ${CERT_FILE}
chown ${VMWARE_POSTGRES_OS_ADMIN}:${VMWARE_POSTGRES_OS_GROUP} \
      ${KEY_FILE} ${CERT_FILE}

exit 0
