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


[ -e ~/.pgpass ] && exit 0

. lib/common

set -e

POSTGRES_ROOT_PASSWORD="$(gen_password)"

##
## Setting up access from host
##

ddb < <(echo "ALTER USER postgres WITH ENCRYPTED password '$POSTGRES_ROOT_PASSWORD'")

sed -ri 's%^host all all 0\.0\.0\.0/0 trust$%host all all 0.0.0.0/0 md5%g' \
    "$SERVICE_DATASTORE/var/lib/postgresql/data/pg_hba.conf"

docker restart "$container_id"


## XXXvlab: this won't help support multiple project running on the
## same host
cat <<EOF > ~/.pgpass
*:*:*:postgres:$POSTGRES_ROOT_PASSWORD
EOF

chmod 600 ~/.pgpass

##
## pgm
##

echo 'prefix_pg_local_command=" "  ## otherwise, will default to sudo -u postgres ' > /root/.pgm.rc

info "New root password for postgres. "