#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service


# Please note that postgres detect on its own if its datadir needs to be populated


. lib/common

set -e


if ! [ -f "$LOCAL_DB_PASSFILE" ]; then
    POSTGRES_ROOT_PASSWORD="$(gen_password)"

    ## required by image of postgres for first run
    server_docker_opts=("${server_docker_opts[@]}" -e POSTGRES_HOST_AUTH_METHOD=trust)
    ddb < <(echo "ALTER USER postgres WITH ENCRYPTED password '$POSTGRES_ROOT_PASSWORD'")
    cat <<EOF > "$LOCAL_DB_PASSFILE"
*:*:*:postgres:$POSTGRES_ROOT_PASSWORD
EOF
    chmod 600 "$LOCAL_DB_PASSFILE"
    info "New root password for postgres."

    ## resetting ``server_docker_opts``, and forcing stop to remove the
    ## POSTGRES_HOST_AUTH_METHOD arg.
    docker stop "$container_id"
    docker rm "$container_id"
    server_docker_opts=()
    _set_server_db_params
fi


if ! egrep "^host all all (0.0.0.0/0|all) md5\$" "$PG_HBA" >/dev/null 2>&1; then
     if egrep "^host all all (0.0.0.0/0|all) trust\$" "$PG_HBA" >/dev/null 2>&1; then
         sed -ri 's%^host all all (0\.0\.0\.0/0|all) trust$%host all all \1 md5%g' \
             "$PG_HBA"
         if is_db_locked; then
             ensure_db_docker_running
             docker restart "$container_id"
             info "Restarted container $container_id"
         fi
         info "Accepting connection from outside."
     else
         die "Can't ensure connection from outside. Please update the charm init script."
     fi
fi