#!/bin/bash

if [ -n "${REDIS_SERVER_PORT}" ] && [ "${REDIS_SERVER_PORT}" != "6379" ]; then
    sed -i 's/port 6379/port '${REDIS_SERVER_PORT}'/g' /etc/redis/redis.conf
fi

if [ -n "${RABBITMQ_SERVER_URL}" ]; then
    rabbitmq_port="$(echo ${RABBITMQ_SERVER_URL} | sed -e 's,^.*:,:,g' -e 's,.*:\([0-9]*\).*,\1,g' -e 's,[^0-9],,g')"
    sed -i 's/.*NODE_PORT=5672/NODE_PORT='${rabbitmq_port}'/g' /etc/rabbitmq/rabbitmq-env.conf
    sed -i 's/.*NODENAME=rabbit/NODENAME=rabbit'${rabbitmq_port}'/g' /etc/rabbitmq/rabbitmq-env.conf
    sed --follow-symlinks -i 's/.*RABBITMQ_PRELAUNCH_NODENAME=.*/RABBITMQ_PRELAUNCH_NODENAME="rabbitmqprelaunch'${rabbitmq_port}'@localhost"/g' /usr/lib/rabbitmq/bin/rabbitmq-server
    echo "IO_THREAD_POOL_SIZE=10" >> /etc/rabbitmq/rabbitmq-env.conf
fi

if [ -n "${DB_PORT}" ] && [ "${DB_PORT}" != "5432" ]; then
    sed -i 's/port = 5432/port = '${DB_PORT}'/g' /etc/postgresql/12/main/postgresql.conf
fi

if [ -n "${NGINX_PORT}" ]; then
    sed -i 's/:80;/:'${NGINX_PORT}';/g;s/:80 /:'${NGINX_PORT}' /g' /etc/nginx/conf.d/ds.conf
    sed -i 's/SERVICE_PORT=${1:-80}/SERVICE_PORT=${1:-'${NGINX_PORT}'}/g;' /usr/bin/monitoring/service-locker.sh
fi

if [ -n "${DOCSERVICE_PORT}" ]; then
    sed -Ei 's/server localhost:8000(.*?);/server localhost:'${DOCSERVICE_PORT}'\1;/g' /etc/nginx/includes/http-common.conf
fi

if [ -n "${SPELLCHECKER_PORT}" ]; then
    sed -Ei 's/server localhost:8080(.*?);/server localhost:'${SPELLCHECKER_PORT}'\1;/g' /etc/nginx/includes/http-common.conf
fi

if [ -n "${FILTER_PROXY_PORT}" ]; then
    sed -Ei 's/listen (.*?):8200(.*?);/listen \1:'${FILTER_PROXY_PORT}'\2;/g' /etc/nginx/sites-enabled/filter-proxy.conf
fi


if [ -n "${NGINX_HOOKS_PORT}" ]; then
    sed -i 's/:3199;/:'${NGINX_HOOKS_PORT}';/g' /etc/nginx/sites-enabled/90-hooks.conf
fi

if [ -n "${NGINX_LOGGIVER_PORT}" ]; then
    sed -i 's/3132/'${NGINX_LOGGIVER_PORT}'/g' \
        /etc/nginx/sites-enabled/20-loggiver3132.conf \
        /etc/monrun/conf.d/loggiver.conf
fi
