#!/bin/bash
################################################################################
# Copyright (c) 2013-2017 VMware, Inc. All rights reserved.
################################################################################
# Sanity checks and processing before starting a PostgreSQL instance.

ENCODING=UTF8
THIS_DIR=`dirname $0`

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

# 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

# Remove any previous health status file.  If PostgreSQL is restarted
# we want to be sure that it gets in a consistent state so as applications
# can connect to it safely.
rm -f /dev/shm/vmware-postgres-health-status.xml

# First clean up any zombie processes that could prevent Postgres to
# start up.
${VMWARE_POSTGRES_BASE}/scripts/pg_clean_zombies KILL $VMWARE_POSTGRES_OS_ADMIN

# Capture some status data from Postgres
${VMWARE_POSTGRES_BASE}/scripts/pg_fetch_status

# Refresh the SSL certificates (vCenter)
${VMWARE_POSTGRES_BASE}/scripts/pg_refresh_certs

# Set up path for temporary statistics
${VMWARE_POSTGRES_BASE}/scripts/pg_temp_stats

# And do the auto-tuning of the instance.
${VMWARE_POSTGRES_BASE}/scripts/pg_tuning

# Send telemetry data of Postgres for start up
${VMWARE_POSTGRES_BASE}/scripts/pg_telemetry_startup
