#!/usr/bin/bash
# Copyright EnterpriseDB Corporation, 2014-2025. All Rights Reserved.

# version name
EFM=efm-5.2

# declare this to avoid static analysis warnings due to use as outvars from getProps
DB_SERVICE_OWNER=

usage() {
    echo $"Usage: $0 startdbservice          <cluster name>"
    echo $"       $0 stopdbservice           <cluster name>"
    echo $"       $0 dbservicestatus         <cluster name>"
    exit 1
}

#
# look for the last occurrence of a non-commented line. Leading and trailing
# white spaces trimmed.
#
# shell functions can't return string, so rely on clunky outvar
#
# Params
#   $1 outvar - this is the name of the variable to store the result in
#   $2 property name to look for
#   $3 property file to grep in
getProp() {
    local OUTVAR=$1
    local PROP_NAME=$2
    local PROP_FILE=$3
    eval "${OUTVAR}"="$(grep "${PROP_NAME}" "${PROP_FILE}" | grep -v \# | tail -1 | cut -d'=' -f2 | awk '{$1=$1};1')"
}

#
# start database
#
startDbService() {
    local PROP_FILE=$1
    getProp SERVICE_NAME db.service.name "${PROP_FILE}"
    if [ -z "$SERVICE_NAME" ]; then
        # some kind of error grepping the service name from the prop file
        echo 'Cannot find db.service.name value.'
        return 1
    else
        systemctl start "${SERVICE_NAME}"
    fi
}

#
# stop database
#
stopDbService() {
    local PROP_FILE=$1
    getProp SERVICE_NAME db.service.name "${PROP_FILE}"
    if [ -z "$SERVICE_NAME" ]; then
        # some kind of error grepping the service name from the prop file
        echo 'Cannot find db.service.name value.'
        return 1
    else
        systemctl stop "${SERVICE_NAME}"
    fi
}

#
# get database service status (used to help catch typos in service name property)
#
dbServiceStatus() {
    local PROP_FILE=$1
    getProp SERVICE_NAME db.service.name "${PROP_FILE}"
    if [ -z "$SERVICE_NAME" ]; then
        # some kind of error grepping the service name from the prop file
        echo 'Cannot find db.service.name value.'
        return 1
    else
        systemctl status "${SERVICE_NAME}"
    fi
}

#
# process the command
#
# command names correlate to enum values in SudoFunctions.java. If you add new functions
# here, then also add a value in SudoFunctions...
#
if [ $# -gt 1 ]; then
    COMMAND=$1
    PROPS="/etc/edb/${EFM}/$2.properties"
    case "$COMMAND" in
        startdbservice)
            startDbService "${PROPS}"
            exit $?
            ;;
        stopdbservice)
            stopDbService "${PROPS}"
            exit $?
            ;;
        dbservicestatus)
            dbServiceStatus "${PROPS}"
            exit $?
            ;;
        *)
            usage
    esac
else
    usage
fi
