#!/bin/bash

set -e
. /usr/share/yunohost/helpers

if ! dpkg --list | grep -q "ii *postgresql-$PSQL_VERSION "
then
    echo 'postgresql is not installed, skipping'
    exit 0
fi

if [ ! -e "/etc/postgresql/$PSQL_VERSION" ]
then
    ynh_die --message="It looks like postgresql was not properly configured ? /etc/postgresql/$PSQL_VERSION is missing ... Could be due to a locale issue, c.f.https://serverfault.com/questions/426989/postgresql-etc-postgresql-doesnt-exist"
fi


do_pre_regen() {
    return 0
}

do_post_regen() {
    #regen_conf_files=$1
  
    # Make sure postgresql is started and enabled
    # (N.B. : to check the active state, we check the cluster state because
    # postgresql could be flagged as active even though the cluster is in
    # failed state because of how the service is configured..)
    systemctl is-active postgresql@$PSQL_VERSION-main -q || ynh_systemd_action --service_name=postgresql --action=restart
    systemctl is-enabled postgresql -q || systemctl enable postgresql --quiet
  
    # If this is the very first time, we define the root password
    # and configure a few things
    if [ ! -f "$PSQL_ROOT_PWD_FILE" ] || [ -z "$(cat $PSQL_ROOT_PWD_FILE)" ]; then
        ynh_string_random >$PSQL_ROOT_PWD_FILE
    fi

    [ ! -e $PSQL_ROOT_PWD_FILE ] || { chown root:postgres $PSQL_ROOT_PWD_FILE; chmod 440 $PSQL_ROOT_PWD_FILE; }
    
    sudo --login --user=postgres psql -c"ALTER user postgres WITH PASSWORD '$(cat $PSQL_ROOT_PWD_FILE)'" postgres
  
    # force all user to connect to local databases using hashed passwords
    # https://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html#EXAMPLE-PG-HBA.CONF
    # Note: we can't use peer since YunoHost create users with nologin
    #  See: https://github.com/YunoHost/yunohost/blob/unstable/data/helpers.d/user
    local pg_hba=/etc/postgresql/$PSQL_VERSION/main/pg_hba.conf
    ynh_replace_string --match_string="local\(\s*\)all\(\s*\)all\(\s*\)peer" --replace_string="local\1all\2all\3md5" --target_file="$pg_hba"

    ynh_systemd_action --service_name=postgresql --action=reload
}

do_$1_regen ${@:2}