#!/bin/bash
# © Copyright EnterpriseDB UK Limited 2015-2023 - All rights reserved.

source "$1"
postgres_bin_dir=${postgres_bin_dir:-""}
pgdata=${pgdata:-/opt/postgres/data}
pgdata_initialised=false
postgres_running=false

VERSION=$pgdata/PG_VERSION
if [[ -f $VERSION ]]; then
    pgdata_initialised=true
    pgdata_version=$(cat "$VERSION")
    pgdata_user=$(stat -c %U "$VERSION")
    pgdata_wal_dir=$(readlink -f "$pgdata/pg_wal")
    pidfile=$pgdata/postmaster.pid
    if [[ -f $pidfile && -d /proc/$(head -1 "$pidfile") ]]; then
        postgres_running=true
    fi
fi

cluster_name() {
    awk '/^cluster:$/ { cluster=1 ; next } cluster && /^ *name: (.*)$/ { print($2) } /./ { cluster=0 }' "$1"
}

F=/etc/harp/config.yml
if [[ -f $F ]]; then
    harp_consensus_protocol=$(awk -F '"' '/driver: "(.*)"/{print($2)}' $F)
    harp_cluster_name=$(cluster_name $F)
fi

for F in /etc/edb/pgd-config.yml /etc/edb/pgd-cli/pgd-cli-config.yml /etc/edb/pgd-proxy/pgd-proxy-config.yml; do
    if [[ -f $F ]]; then
        pgd_cluster_name=$(cluster_name $F)
    fi
done

if command -v "$postgres_bin_dir"/bdr_config; then
    output=$("$postgres_bin_dir"/bdr_config --version)
    bdr_major_version=$(sed -En "s/BDR_VERSION_COMPLETE=([^\.]*).*/\1/p" <(echo "${output}"))
    bdr_version_num=$(sed -En "s/BDR_VERSION_NUM=(.*)/\1/p" <(echo "${output}"))
fi

grep -Ev '": "*,*$' <<RESULT
{
    "changed": false,
    "ansible_facts": {
        "pgdata_wal_dir": "$pgdata_wal_dir",
        "pgdata_user": "$pgdata_user",
        "pgdata_version": $pgdata_version,
        "pgdata_initialised": $pgdata_initialised,
        "postgres_running": $postgres_running,
        "harp_consensus_protocol": "$harp_consensus_protocol",
        "harp_cluster_name": "$harp_cluster_name",
        "pgd_cluster_name": "$pgd_cluster_name",
        "bdr_major_version": $bdr_major_version,
        "bdr_version_num": $bdr_version_num,
        "pgdata": "$pgdata"
    }
}
RESULT
