#!/bin/sh
#-----------------------------------------------------------------------------
# /var/install/bin/postgresql14-tools-passwd
#
# Creation:     2005-10-09 dv
# Last Update:  2023-07-23 09:11:10
#
# Copyright (c) 2024 the eisfair team, team(at)eisfair(dot)org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#-----------------------------------------------------------------------------

#include eislib
. /var/install/include/eislib
. /etc/config.d/postgresql14

INSTDIR="/usr/lib64/pgsql/14/bin"
PASSWD_FILE="${HOME}/.pgpass"

clrhome
mecho "Here you can set a password for local access to the database."
mecho "This is required for the autovacuum daemon or for cron controlled"
mecho "backups, if local access (host access table) is anything but trust."
mecho ""

if /var/install/bin/ask "Continue" "yes"
then
    echo
    mecho -info "Select database user to set password for:"
    echo "select usename from pg_user;" | \
         ${INSTDIR}/psql template1 postgres

    echo -e 'Database user [postgres]: \c'
    read dbuser

    if [ "$dbuser" = "" ]
    then
        dbuser='postgres'
    fi

    echo ""
    mecho -info "Now enter the new password:"
    password=""
    password2="x"
    while [ "$password" != "$password2" ]
    do
        echo -e "Enter new local password: \c"
        read -s password
        echo ""

        echo -e "Reenter local password: \c"
        read -s password2
        echo ""

        if [ "$password" != "$password2" ]
        then
            mecho -warn "Passwords do not match!"
        fi
    done

    if [ ! -f "${PASSWD_FILE}" ]
    then
        touch "${PASSWD_FILE}"
    fi

    if ! grep -q "^localhost:\*:\*:$dbuser:" "${PASSWD_FILE}" 2>&1 >/dev/null
    then
        echo "localhost:*:*:$dbuser:$password" >> "${PASSWD_FILE}"
    else
        (
           echo "\$0 !~ /localhost:\*:\*:$dbuser/ { print \$0 }"
           echo "/localhost:\*:\*:$dbuser/ {print \"localhost:*:*:$dbuser:$password\"}"
        ) > /tmp/pgpass$$.awk
        awk -f /tmp/pgpass$$.awk "${PASSWD_FILE}" > "/tmp/pgpass$$.tmp"
        cp /tmp/pgpass$$.tmp "${PASSWD_FILE}"

        rm /tmp/pgpass$$.awk
        rm /tmp/pgpass$$.tmp
    fi
    chmod 0600 "${PASSWD_FILE}"

    echo ""
    mecho -info "Password set successfully!"
fi

anykey
exit 0