#!/bin/bash
################################################################################
# Copyright (c) 2020 VMware, Inc. All rights reserved.
################################################################################
# Wrapper script aimed at trigger pg_corruption_telemetry which is used to check
# postgres corruption and push telemetry data if checksum failures detected
# periodically via a cron job.
# This script should be launched as root.

# Load environment variables needed for script
source /etc/profile.d/vmware-vpostgres-config.sh
source /etc/profile.d/VMware-visl-integration.sh

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

LOGFILE=${VMWARE_POSTGRES_LOG}/postgres_telemetry_cron.log

# Call pg_corruption_telemetry.py to check postgres corruption
# and push telemetry data if checksum failures detected.
# all the output will be sent to LOGFILE.
echo "========== Start Running pg_corruption_telemetry $(date -u +"%Y-%m-%dT%H:%M:%SZ") ==========" >> "$LOGFILE"
$VMWARE_PYTHON_BIN ${VMWARE_POSTGRES_BASE}/bin/vmw_vpg_config/pg_corruption_telemetry.py >> "$LOGFILE"

ERRNUM=$?
if [ "$ERRNUM" != 0 ]; then
   echo "Fail to run pg_corruption_telemetry" >> "$LOGFILE"
else
   echo "Success to run pg_corruption_telemetry" >> "$LOGFILE"
fi

echo -e "========== End of running pg_corruption_telemetry ==========" >> "$LOGFILE"

# Ensure proper permissions on the log file
chmod 600 ${LOGFILE}
chown ${VMWARE_POSTGRES_OS_ADMIN}:${VMWARE_POSTGRES_OS_GROUP} \
            ${LOGFILE}
exit 0
