#!/bin/bash

set -e

SENTINEL="/var/lib/wazo-upgrade/restrict-postgres-hba"

[ -e "${SENTINEL}" ] && exit 0

# If PostgreSQL config was customized, do nothing
# The sha256sum comes from the file generated by the Ansible installer until Wazo 20.01
if [ "$(grep -v '^host asterisk postgres' /etc/postgresql/11/main/pg_hba.conf | sha256sum)" != "ac4cd2410dc375f6e1bc2eea0285f4ce3cccf57c45cbfe07aefdf7c8c6f80d9b  -" ] ; then
    exit 0
fi

new_hba_file=$(mktemp)

# Create default HBA
cat <<EOF > $new_hba_file
#
# Ansible managed
#
# PostgreSQL Client Authentication Configuration File
# ===================================================
#
# See: https://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html

local all postgres    peer
local all all    peer
host all all 127.0.0.1/32   md5
host all all ::1/128   md5
EOF

# Add HBA for master host, if we're a slave
grep '^host asterisk postgres' /etc/postgresql/11/main/pg_hba.conf >> $new_hba_file || true

# Apply new config and keep permissions
cat $new_hba_file > /etc/postgresql/11/main/pg_hba.conf
systemctl reload postgresql

touch "${SENTINEL}"
