#!/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 user '$USER'."
    fi
fi


array_read-0 extensions < <(relation-get extensions 2>/dev/null | shyaml get-values-0)

ensure_db_docker_running

## XXXvlab: should send all these into only one docker...
if ! db_has_database "$DBNAME"; then
    INITDB_ARGS=(encoding lc-collate lc-ctype template)
    CREATEDB_OPTS=()
    for option in "${INITDB_ARGS[@]}"; do
        value="$(relation-get "$option" 2>/dev/null)" || true
        if [ -n "$value" ]; then
            CREATEDB_OPTS+=("--$option=$value")
        fi
    done
    db_create "$DBNAME" "${CREATEDB_OPTS[@]}" || exit 1
    if sql=$(relation-get init-sql); then
        ddb "$DBNAME" > /dev/null < <(e "$sql") || exit 1
    fi
fi
if [ "${#extensions[@]}" -gt 0 ]; then
    db_install_extensions "$DBNAME" "${extensions[@]}" || exit 1
fi
if ! db_has_user "$USER"; then
    info "Creating a new user $USER."
    db_create_user "$USER" "$PASSWORD" || exit 1
else
    info "Updating password of user $USER."
    db_change_password "$USER" "$PASSWORD" || exit 1
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"