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

source "$1"

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

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",
        "pgdata": "$pgdata"
    }
}
RESULT
