#!/bin/bash
set -uo pipefail
#==============================================================#
# File      :   pgsql-hba
# Desc      :   Refresh Postgres/Pgbouncer HBA Rules
# Ctime     :   2021-11-02
# Mtime     :   2024-08-02
# Path      :   bin/pgsql-hba
# Deps      :   ansible-playbook, pgsql.yml
# License   :   Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright :   2018-2026  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
APP_NAME="$(basename $0)"
APP_DIR="$(cd $(dirname $0) && pwd)"
PIGSTY_HOME=$(cd $(dirname ${APP_DIR}) && pwd)


#--------------------------------------------------------------#
# Usage
#--------------------------------------------------------------#
# bin/pgsql-hba <cls>          # refresh hba rules for cluster 'cls'
# bin/pgsql-hba <cls> [ip...]  # refresh hba rules for specific instances


#--------------------------------------------------------------#
# Utils
#--------------------------------------------------------------#
__CN='\033[0m';__CK='\033[0;30m';__CR='\033[0;31m';__CG='\033[0;32m';
__CY='\033[0;33m';__CB='\033[0;34m';__CM='\033[0;35m';__CC='\033[0;36m';__CW='\033[0;37m';
function log_info() {  printf "[${__CG} OK ${__CN}] ${__CG}$*${__CN}\n";   }
function log_warn() {  printf "[${__CY}WARN${__CN}] ${__CY}$*${__CN}\n";   }
function log_error() { printf "[${__CR}FAIL${__CN}] ${__CR}$*${__CN}\n";   }
function log_debug() { printf "[${__CB}HINT${__CN}] ${__CB}$*${__CN}\n"; }
function log_input() { printf "[${__CM} IN ${__CN}] ${__CM}$*\n=> ${__CN}"; }
function log_hint()  { printf "${__CB}$*${__CN}\n"; }
function log_line()  { printf "${__CM}[$*] ===========================================${__CN}\n"; }
function is_valid_ip(){
    if [[ "$1" =~ (([0-9]|[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5]) ]]; then
        return 0
    else
        return 1
    fi
}

#--------------------------------------------------------------#
# Param
#--------------------------------------------------------------#
PG_CLUSTER=${1-''}
if [[ -z "${PG_CLUSTER}" ]]; then
	log_error "pg_cluster is empty"
	log_hint "Usage:"
	log_hint "    bin/pgsql-hba <cls>          # refresh pg/pgb hba rules for cluster 'cls'"
	log_hint "    bin/pgsql-hba <cls> [ip...]  # refresh pg/pgb hba rules for specific instances"
	exit 1
fi


#--------------------------------------------------------------#
# Reload Cluster HBA                  [ 1 arg = reload cls hba ]
#--------------------------------------------------------------#
# if only 1 arg is given, arg1 = pg_cluster
# hba rules of the entire pgsql cluster will be reloaded
if (($# == 1)); then
	log_line "EXECUTE"
	log_warn "reload hba rules for '${PG_CLUSTER}'"
  log_hint "$ ./pgsql.yml -l '${PG_CLUSTER}' -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload"
  "${PIGSTY_HOME}/pgsql.yml" -l "${PG_CLUSTER}" -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
	RETURN_CODE=$?

  log_line "SUMMARY"
  if [[ ${RETURN_CODE} -eq 0 ]]; then
    log_info "reload hba rules for '${PG_CLUSTER}' complete"
    exit 0
  else
    log_error "fail to reload hba rules for '${PG_CLUSTER}'"
    log_warn "current traffic may not be affected immediately"
    log_warn "BUT IT'S VERY IMPORTANT TO FIX THIS ASAP!"
    exit 2
  fi

	log_info "reload pgsql hba rules for ${PG_CLUSTER} complete!"
	exit ${RETURN_CODE}
fi



#--------------------------------------------------------------#
# Reload Specific Instances           [2+ args = reload ins hba]
#--------------------------------------------------------------#
# if more than 1 args is given, arg1 = pg_cluster, arg2+ = ip list
# each instance (with corresponding ip) hba rules will be reloaded
IP_LIST=""
TARGET_PATTERN="&${PG_CLUSTER}"
EXISTS_PATTERN="${PG_CLUSTER}"
for ((i=2; i<=$#; i++))
do
  if ! is_valid_ip "${!i}"; then
    log_error "invalid ip address given: ${!i}"
    exit 3
  fi
  IP_LIST="${IP_LIST} ${!i}"
  TARGET_PATTERN="${!i},${TARGET_PATTERN}"
  EXISTS_PATTERN="${EXISTS_PATTERN},!${!i}"
done

# Reload Postgres HBA
log_line "EXECUTE"
log_warn "reload hba rules on specific ${PG_CLUSTER} members"
log_hint "$ ./pgsql.yml -l '${TARGET_PATTERN}' -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload"
"${PIGSTY_HOME}/pgsql.yml" -l "${TARGET_PATTERN}" -t pg_hba,pg_reload,pgbouncer_hba,pgbouncer_reload
RETURN_CODE=$?

log_line "SUMMARY"
if [[ ${RETURN_CODE} -eq 0 ]]; then
  log_info "reload hba rules for ${IP_LIST} of ${PG_CLUSTER} complete"
  exit 0
else
  log_error "fail to reload hba rules for ${IP_LIST} of ${PG_CLUSTER}"
  log_warn "current traffic may not be affected immediately"
  log_warn "BUT IT'S VERY IMPORTANT TO FIX THIS ASAP!"
  exit 4
fi