#!/bin/bash

set -e

PEERTUBE_CONFIG_DIR=/etc/peertube

HOST_CONFIG_DIR=$SERVICE_CONFIGSTORE/$PEERTUBE_CONFIG_DIR

PASSWORD="$(relation-get password)"
USER="$(relation-get user)"
DBNAME="$(relation-get dbname)"

cat <<EOF >> "$HOST_CONFIG_DIR/local.yaml"

database:
  hostname: '$TARGET_SERVICE_NAME'
  ## We had to patch peertube to have a direct dbname (doh!)
  dbname: '$DBNAME'
  port: 5432
  username: '$USER'
  password: '$PASSWORD'

EOF

## XXXvlab: needed only for psql access to check if database is ready
## before launching the app.
uid=$(docker_get_uid "$SERVICE_NAME" peertube) || exit 1

chown "$uid" "$SERVICE_CONFIGSTORE/root/.pgpass" || exit 1

config-add "
services:
  $MASTER_BASE_SERVICE_NAME:
    environment:
      PGUSER: $USER
      PGHOST: $TARGET_SERVICE_NAME
      PGDATABASE: $DBNAME
    volumes:
      - $SERVICE_CONFIGSTORE/root/.pgpass:/var/lib/peertube/.pgpass
"

info "Configured $SERVICE_NAME code for $TARGET_SERVICE_NAME access."