#!/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 2>/dev/null) || {
    DBNAME="$BASE_SERVICE_NAME"
    relation-set dbname "$DBNAME"
}

USER=$(relation-get user 2>/dev/null) || {
    USER="$BASE_SERVICE_NAME"
    relation-set user "$USER"
}


PASSWORD="$(relation-get password 2>/dev/null)"

. lib/common

set -e

## 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



ensure_db_docker_running || exit 1
if [ "$?" == 0 ] && check_access "$DBNAME" "$USER" "$PASSWORD"; then
    info "Access to database '$DBNAME' from user '$USER' verified working."
    exit 0
fi


db_create "$DBNAME"

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



relation-set password "$PASSWORD"