#!/bin/sh

[ -s /chbase-done ] && CURRENT_BASE=$(cat /chbase-done) || CURRENT_BASE="/"
[ -n "${BASEURL}" ] || BASEURL="/"
[ "${BASEURL}" == "/" ] && BASEURL2="@baseurl" || BASEURL2="${BASEURL}"

run() {
    local NEWBASE=$1
    local FILE=$2

    if [ -d "${FILE}" ]
    then
        for f in "${FILE}/"*
        do
            case "${f}" in
                "${FILE}/"*.html|"${FILE}/"*.js)
                    run "${NEWBASE}" "${f}";;
            esac
        done
    elif [ -f "${FILE}" ]
    then
        echo "Updating base path for $FILE..."
        sed -ri "s@<base href=\"${CURRENT_BASE}\">@<base href=\"${NEWBASE}\">@;s@\"${CURRENT_BASE}_app/@\"${NEWBASE}_app/@;s@base: \"${CURRENT_BASE%/}\"@base: \"${NEWBASE%/}\"@" ${FILE}
    fi
}

[ "${CURRENT_BASE}" != "${BASEURL}" ] && {
    run "${BASEURL}" /srv/htdocs-frontend
    echo "${BASEURL}" > /chbase-done
}

exec /srv/receiver $@
