#!/bin/sh

[ -f "/base_changed" ] && exit 0

[ -z "${FIC_BASEURL}" ] && exit 0
[ -z "${PATH_STATIC}" ] && { >&2 echo "PATH_STATIC not defined"; exit 1; }
[ -n "${CURRENT_BASE}" ] || CURRENT_BASE="/"

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

    if [ -d "${FILE}" ]
    then
        for f in "${FILE}/"*
        do
            case "${f}" in
                "${FILE}/"*.html|"${FILE}/"*.js|"${FILE}/"*.css)
                    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
}

run "${FIC_BASEURL}" "${PATH_STATIC}"
touch "/base_changed"

if [ "${FIC_BASEURL}" == "/" ] && [ -f /etc/nginx/conf.d/default.conf ]
then
    sed -i "s:location / {:location @notneeded {:" /etc/nginx/conf.d/default.conf
fi

[ -n "${FIC_CUSTOM_HEAD}" ] && sed -i "s|</head>|${FIC_CUSTOM_HEAD}</head>|" "${PATH_STATIC}/index.html"
[ -n "${FIC_CUSTOM_BODY}" ] && sed -i "s|</body>|${FIC_CUSTOM_BODY}</body>|" "${PATH_STATIC}/index.html"

exit 0
