#!/bin/bash

## When writing relation script, remember:
##  - they should be idempotents
##  - they can be launched while the dockers is already up
##  - they are launched from the host
##  - the target of the link is launched first, and get a chance to ``relation-set``
##  - both side of the scripts get to use ``relation-get``.


DBNAME=$(relation-get dbname) || {
    DBNAME="$BASE_SERVICE_NAME"
    relation-set dbname "$DBNAME"
}

USER=$(relation-get user) || {
    USER="$BASE_SERVICE_NAME"
    relation-set user "$USER"
}

. lib/common

set -e

## YYY: check that password was not already generated/set for the same user
## use session state storage.

## is there a previous password set for user $USER ?

NO_PREVIOUS_PASS=
PREVIOUS_PASSWORD_PATH="$state_tmpdir/$SERVICE_NAME/pwd/$USER"
PREVIOUS_PASSWORD=$(cat "$PREVIOUS_PASSWORD_PATH" 2>/dev/null) || NO_PREVIOUS_PASS=true

if PASSWORD="$(relation-get password 2>/dev/null)"; then
    if [ -z "$NO_PREVIOUS_PASS" -a "$PREVIOUS_PASSWORD" != "$PASSWORD" ]; then
        die "Inconsistent password specification for user '$USER' on ${DARKYELLOW}$TARGET_SERVICE_NAME$NORMAL."
    fi
else
    if [ "$PREVIOUS_PASSWORD" ]; then
        PASSWORD="${PREVIOUS_PASSWORD}"
    else
        PASSWORD="$(gen_password)"
        info "Generated a new password for use '$USER'."
    fi
fi


POSTGIS=$(relation-get postgis 2>/dev/null) || true
UNACCENT=$(relation-get unaccent 2>/dev/null) || true


ensure_db_docker_running

## XXXvlab: should send all these into only one docker...
db_has_database "$DBNAME" || UNACCENT="$UNACCENT" POSTGIS="$POSTGIS" db_create "$DBNAME"
if ! db_has_user "$USER"; then
    info "Creating a new user $USER."
    db_create_user "$USER" "$PASSWORD"
else
    info "Updating password of user $USER."
    db_change_password "$USER" "$PASSWORD"
fi

db_grant_rights "$DBNAME" "$USER"
info "Granted rights on database '$DBNAME' to user '$USER'."


##
## PGPASS
##

pgpass_line="*:*:*:$USER:$PASSWORD"
pgpass_file="$CONFIGSTORE/$BASE_SERVICE_NAME/root/.pgpass"

if [ -e "$pgpass_file" ]; then
    sed -ri "/^.+:.+:.+:$USER:.*$/d" "$pgpass_file"
fi
mkdir -p "$(dirname "$pgpass_file")"
echo "$pgpass_line" >> "$pgpass_file"
chmod 600 "$pgpass_file"


##
## Saving password
##

relation-set password "$PASSWORD"
mkdir -p "$(dirname "$PREVIOUS_PASSWORD_PATH")"
echo "$PASSWORD" > "$PREVIOUS_PASSWORD_PATH"