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


admin_password=$(options-get admin-password 2>/dev/null ) || exit 1

CONTROL_PASSWORD_FILE="$SERVICE_DATASTORE/.control-pass"
## Was it already properly propagated to database ?
control_password=$(H "${admin_password}")
if ! [ -e "$CONTROL_PASSWORD_FILE" ] || [ "$control_password" != "$(cat "$CONTROL_PASSWORD_FILE")" ]; then

    hash="$(htpasswd -nbBC 10 USER "$admin_password" | cut -f 2- -d :)" || {
        err "Couldn't generate hash for admin password."
        exit 1
    }

    if ! sql < <(e "
    UPDATE passwords SET value = '$hash'
    WHERE user_id = 1
      AND status = 'ACTIVE'
      AND password_type_id in (
        SELECT id FROM password_types
        WHERE input_method = 'TEXT_BOX'
          AND password_mode = 'MANUAL');
    "); then
        debug "Failed to set password for admin users."
        exit 1
    fi
    mkdir -p "${CONTROL_PASSWORD_FILE%/*}"
    e "$control_password" > "$CONTROL_PASSWORD_FILE"
fi



if ! url=$(named-relation-get "web-proxy" url); then
    ## no proxy, so we don't know our url, might want to do it in
    ## post-deploy
    exit 0
fi

## In ``configurations`` table, columns login_url, logout_url, root_url
if ! sql < <(e "
UPDATE configurations
SET
     root_url = '$url'
"); then
    debug "Failed to set password for admin users."
    exit 1
fi