#!/bin/bash

##
## Get domain in option of relation "web-proxy"
##

## XXXvlab: there is a tiny lapse of time where database is not yet
## installed, and admin password is the default value.


. lib/common

set -ex

if url=$(named-relation-get "web-proxy" url); then
    ## proxy ! so we probably already set up the url in
    ## pre_deploy
    exit 0
fi

container=$(get_running_containers_for_service "$SERVICE_NAME" | head -n 1)
container_network_ip=$(get_docker_ip "$container")
container_ip=${container_network_ip#*:}

## XXXvlab: hard written duplicate value
url="$container_ip:8080"

CONTROL_URL_FILE="$SERVICE_DATASTORE/.control-url"
## Was it already properly propagated to database ?
control_url=$(H "${url}")
if ! [ -e "$CONTROL_URL_FILE" ] || [ "$control_url" != "$(cat "$CONTROL_URL_FILE")" ]; then
    ## In ``configurations`` table, columns login_url, logout_url, root_url

    if ! sql < <(e "
    UPDATE configurations
    SET
         root_url = 'http://$url'
    "); then
        debug "Failed to set root url."
        exit 1
    fi
    e "$control_password" > "$CONTROL_URL_FILE"
fi