#!/bin/bash

##
## Get domain in option of relation "publish-dir"
##

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

## XXXvlab: can't get real config here
if ! read-0 publish_dir_ts _ _ < <(get_service_relation "$SERVICE_NAME" "publish-dir"); then
    err "Couldn't find relation ${DARKCYAN}publish-dir${NORMAL}."
    exit 1
fi

publish_dir_relation_dir=$(get_relation_data_dir "$SERVICE_NAME" "$publish_dir_ts" "publish-dir") || {
    err "Failed to find relation file"
    exit 1
}

publish_dir_relation_config=$(cat "$publish_dir_relation_dir/data") || exit 2

domain=$(e "$publish_dir_relation_config" | shyaml get-value domain) || {
    err "Couldn't get domain information in ${DARKCYAN}publish-dir${NORMAL} relation's data."
    exit 1
}

url=$(e "$publish_dir_relation_config" | shyaml get-value url) || {
    err "Couldn't get domain information in ${DARKCYAN}publish-dir${NORMAL} relation's data."
    exit 1
}


##
## Local charm config
##

admin_password=$(options-get admin-password 2>/dev/null ) || exit 1
admin_email=$(options-get admin-email 2>/dev/null ) || true
admin_email=${admin_email:-"admin@$domain"}



CONTROL="$SERVICE_DATASTORE/.control"
## Was it already properly propagated to database ?
control=$(H "${admin_password}" "${admin_email}")
if [ -e "$CONTROL" ] && [ "$control" == "$(cat "$CONTROL")" ]; then
    exit 0
fi

## XXXvlab: can't get real config here
if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "mysql-database"); then
    err "Couldn't find relation ${DARKCYAN}mysql-database${NORMAL}."
    exit 1
fi


##
## We need mysql relation config also
##

relation_file=$(get_relation_data_file "$SERVICE_NAME" "$ts" "mysql-database") || {
    err "Failed to find relation file"
    exit 1
}

mysql_config=$(cat "$relation_file") || exit 2

DBNAME="$(e "$mysql_config" | shyaml get-value dbname)" || {
    err "Couldn't retrieve information of ${DARKCYAN}mysql-database${NORMAL}'s relation."
    exit 1
}

CONFIG="$SERVICE_DATASTORE/opt/apps/piwigo/local/config/database.inc.php"
if [ -f "$CONFIG" ]; then
    debug "Database already configured."

    export SERVICE_NAME="$ts"
    export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
    DOCKER_BASE_IMAGE=$(service_base_docker_image "$SERVICE_NAME")
    export DOCKER_BASE_IMAGE

    target_charm=$(get_service_charm "$ts") || exit 1
    target_charm_path=$(charm.get_dir "$target_charm") || exit 1

    set +e

    . "$target_charm_path/lib/common"

    set -e

    ensure_db_docker_running

    if ! out=$(ddb "$DBNAME" < <(e "UPDATE users SET password=md5('$admin_password'), mail_address='$admin_email' WHERE id=1")); then
        debug "Failed to set password for admin users."
        exit 1
    fi
    e "$control" > "$CONTROL"
    exit 0
fi


##
## We are in post_deploy, so our service is up, we need to get
## the ``network`` and ``container``'s id to communicate with
## him.
##

container_id=$(
    for container_id in $(get_running_containers_for_service "$MASTER_BASE_SERVICE_NAME"); do
        e "$container_id"
        break
    done
)

read-0 network container_ip < <(get_container_network_ip "$container_id")


##
## We'll need password from mysql database config
##

PASSWORD="$(e "$mysql_config" | shyaml get-value password)" &&
USER="$(e "$mysql_config" | shyaml get-value user)" || {
    err "Couldn't retrieve information of ${DARKCYAN}mysql-database${NORMAL}'s relation."
    exit 1
}

default_lang=$(options-get default-lang) || exit 1


## We deliberately are not setting these: (they will be considered off)
# newsletter_subscribe	"on"
# send_password_by_mail	"on"


debug "Running install.php"
out=$(docker run --network "$network" docker.0k.io/curl -s -X POST -H "Host: $domain" -L \
       -F language="$default_lang" \
       -F dbhost="$ts" \
       -F dbuser="$USER" \
       -F dbpasswd="$PASSWORD" \
       -F dbname="$DBNAME" \
       -F prefix="" \
       -F admin_name="admin" \
       -F admin_pass1="$admin_password" \
       -F admin_pass2="$admin_password" \
       -F admin_mail="$admin_email" \
       -F install="Start+installation" \
       "$url/install.php") || {
    err "Failed to run install.php script"
    exit 1
}


#e "$out" > "$SERVICE_DATASTORE/out.html"
# debug "written $SERVICE_DATASTORE/out.html"
had_error=
while read-0 error_msg; do
    had_error=1
    err "Installation failed with these errors:"
    echo "- ${error_msg}" >&2
done < <(e "$out" | xpath "//div[@class='errors']/ul/li/text()")

if [ "$had_error" ]; then
    exit 1
fi

debug "No error catched on \`\`install.php\`\` result."
e "$control" > "$CONTROL"

exit 0