#!/bin/sh

# Volumes
USHAHIDI_CONF="${VOLUMES_DIR}/ushahidi/ushahidi_conf"

# Variables
HTTP_HOST="${HOST}"
[ "${PORT}" != "443" ] && HTTP_HOST="${HTTP_HOST}:${PORT}"

# Start MariaDB container if needed
if [ "$(spoc-container status ushahidi-mariadb)" != "RUNNING" ]; then
    STOP_MARIADB=1
    spoc-container start ushahidi-mariadb
fi

# Replacements
sed -i "s|\(^\s\+\"backend_url\": \).*|\1\"https://${HTTP_HOST}/platform\",|" ${USHAHIDI_CONF}/config.json
API_URL="\"https:\\\/\\\/${HTTP_HOST}\\\/platform\\\/api\\\/v3\\\/config\\\/data-provider\""
QUERY="UPDATE \`config\` SET \`config_value\` = '${API_URL}' WHERE \`group_name\` LIKE 'data-provider' AND \`config_key\` LIKE 'url'"
spoc-container exec ushahidi-mariadb -- mysql -e "${QUERY}" ushahidi

JSON="{\"incoming_type\":\"IMAP\",\"incoming_server\":\"localhost\",\"incoming_port\":143,\"incoming_security\":\"None\",\"incoming_username\":\"${EMAIL}\",\"incoming_password\":\"password\",\"outgoing_type\":\"SMTP\",\"outgoing_server\":\"host\",\"outgoing_port\":25,\"outgoing_security\":\"None\",\"outgoing_username\":\"${EMAIL}\",\"outgoing_password\":\"password\",\"from\":\"${EMAIL}\",\"from_name\":\"Ushahidi\"}"
QUERY="UPDATE \`config\` SET \`config_value\` = '${JSON}' WHERE \`group_name\` LIKE 'data-provider' AND \`config_key\` LIKE 'email'"
spoc-container exec ushahidi-mariadb -- mysql -e "${QUERY}" ushahidi
QUERY="UPDATE \`config\` SET \`config_value\` = '\"${EMAIL}\"' WHERE \`group_name\` LIKE 'site' AND \`config_key\` LIKE 'email'"
spoc-container exec ushahidi-mariadb -- mysql -e "${QUERY}" ushahidi
sed -i "s|\(^\s\+\"google_analytics_id\": \).*|\1\"${GMAPS_API_KEY}\"|" ${USHAHIDI_CONF}/config.json

# Stop MariaDB container if needed
if [ -n "${STOP_MARIADB}" ]; then
    echo spoc-container stop ushahidi-mariadb
fi
