#!/bin/sh

# You can define the current base URL in your environment
[ -n "${CURRENT_BASE}" ] || CURRENT_BASE="/"

usage() {
    echo "$0 NEWBASE STATICDIR"
    echo
    echo "  This script can be used to change the base URL of the frontend."
    echo "  Gives as PATH, the path to the static directory."
    echo "  You should use this script only one time (ie. from a fresh git repository),"
    echo "  as it doesn't erase previously defined base: it assumes the current base is /."
    echo
    echo "  For example:"
    echo
    echo "      $0 /$(date -d 'next year' +%Y)/" static/
    echo
}

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

    if [ -d "${FILE}" ]
    then
	for f in "${FILE}/"*.html "${FILE}/"*.js
	do
	    run "${NEWBASE}" "${f}"
	done
	[ -d "${FILE}/js/" ] && run "${NEWBASE}" "${FILE}/js"
	[ -d "${FILE}/views/" ] && run "${NEWBASE}" "${FILE}/views"
    elif [ -f "${FILE}" ]
    then
	sed -ri "s@(href|src)=\"${CURRENT_BASE}@\1=\"${NEWBASE}@g;s@\\\$http.get\(\"${CURRENT_BASE}@\$http.get\(\"${NEWBASE}@g;s@\\\$http\((.*)\"${CURRENT_BASE}@\$http(\1\"${NEWBASE}@g" ${FILE}
    fi
}

if [ $# -gt 1 ]
then
    run $1 $2
else
    usage
    exit 1
fi
