#!/usr/bin/env bash
set -uo pipefail
#==============================================================#
# File      :   pg-init
# Desc      :   shell script to init postgres cluster
# Time      :   {{ '%Y-%m-%d %H:%M' | strftime }}
# Host      :   {{ pg_instance }} @ {{ inventory_hostname }}:{{ patroni_port }}
# Path      :   /pg/bin/pg-init
# Deps      :   psql, /pg/tmp/pg-init-*.sql
# License   :   Apache-2.0 @ https://pigsty.io/docs/about/license/
# Copyright :   2018-2026  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
PROG_NAME="$(basename $0)"
PROG_DIR="$(cd $(dirname $0) && pwd)"


#--------------------------------------------------------------#
#                        Default Roles                         #
#--------------------------------------------------------------#
{{ pg_bin_dir}}/psql -h {{ pg_localhost|default('/var/run/postgresql') }} -p {{ pg_port|default(5432) }} postgres -qAXwtf /pg/tmp/pg-init-roles.sql


#--------------------------------------------------------------#
#                        System Template                       #
#--------------------------------------------------------------#
# system default template
{{ pg_bin_dir }}/psql -h {{ pg_localhost|default('/var/run/postgresql') }} -p {{ pg_port|default(5432) }} template1 -qAXwtf /pg/tmp/pg-init-template.sql

# make postgres same as templated database (optional)
{{ pg_bin_dir }}/psql -h {{ pg_localhost|default('/var/run/postgresql') }} -p {{ pg_port|default(5432) }} postgres -qAXwtf /pg/tmp/pg-init-template.sql

{% if pg_mode == 'citus' and pg_primary_db != 'postgres' %}
# pg_primary_db are created by patroni, init with templates
{{ pg_bin_dir }}/psql -h {{ pg_localhost|default('/var/run/postgresql') }} -p {{ pg_port|default(5432) }} {{ pg_primary_db }} -qAXwtf /pg/tmp/pg-init-template.sql
{% endif %}

#--------------------------------------------------------------#
#                        Customize Logic                       #
#--------------------------------------------------------------#
# add your template logic here
