name=${1:-replique}
port=${2:-5432}
user=$(whoami)
version=$(pg_config --version | grep -Po "\d+" | head -n1)
echo "nom du cluster: $name"
echo "port du cluster primaire: $port"
echo "version: $version"

sudo -u postgres pg_conftool set synchronous_standby_names '*'  # ça fait planter en mono serveur!


conninfo="host=localhost user=$user password=$user"
echo "primary_conninfo: $conninfo"

if pg_lsclusters "$version" "$name" >/dev/null 2>&1; then
    echo "Cluster $version/$name déjà présent, suppression..."
    sudo -u postgres pg_dropcluster --stop "$version" "$name"
fi

# Permet de se connecter depuis n'importequel ip sur le serveur PostgreSQL 
sudo -u postgres pg_createcluster $version $name
sudo -u postgres pg_ctlcluster $version $name start
# Met en place des paramètre de configuration
port_rep=$(pg_lsclusters -h | grep -P "\d+\s+$name" | cut -f3 -d" ")
echo "port du cluster secondaire: $port_rep"

pg_hba=$(sudo -u postgres psql -p $port_rep -t -P format=unaligned -c 'show hba_file';)

# Met en place des paramètre de configuration

sudo cp $pg_hba /tmp/
sudo sed -i 's/^/#/g' $pg_hba # commente pg_hba.conf

sudo tee -a "$pg_hba" > /dev/null <<EOF
### AUTOMATICALLY ADDED ####
local   all             postgres                                peer
host    all             all             all                     scram-sha-256
host    replication     all             all                     scram-sha-256
local   all             all                                     peer
EOF
data_dir_rep=$(sudo -u postgres psql -p $port_rep -t -P format=unaligned -c 'show data_directory;';)
echo data dir of replica $data_dir_rep
sudo -u postgres pg_ctlcluster $version $name stop
sudo rm -rf $data_dir_rep
# Dupplique les données de la primaire.
sudo -u postgres pg_basebackup  -p $port -D $data_dir_rep -R
sudo chown -R postgres:postgres $data_dir_rep
sudo -u postgres pg_conftool $version $name set primary_conninfo "$conninfo"
sudo -u postgres pg_conftool $version $name set listen_addresses '*'
sudo -u postgres pg_conftool $version $name set wal_level replica

# Relance le serveur.
sudo -u postgres pg_ctlcluster $version $name start
