#!/bin/bash
#
# This script updates all timestamps in the HTML files of OX App Suite.
#
# This work is provided under the terms of the CREATIVE COMMONS PUBLIC
# LICENSE. This work is protected by copyright and/or other applicable
# law. Any use of the work other than as authorized under this license
# or copyright law is prohibited.
#
# http://creativecommons.org/licenses/by-nc-sa/2.5/
#
# Copyright 2016 OX Software GmbH, Germany. info@open-xchange.com
#

NOW=$(date -u +%Y%m%d.%H%M%S)

usage(){
    cat <<EOF

    Command usage: $(basename ${0}) [option]

    -h|--help            : displays this usage message
    --timestamp=<value>  : default: e.g. ${NOW}

    This tool creates timestamps on OX App Suite frontend Javascript-Code
    for browser cache invalidation.
EOF
}

for argument in "${@}"; do
    case ${argument} in
        -h|--help)
            usage
            exit 0
        ;;
        --timestamp=*)
            NOW=${argument##--timestamp=}
        ;;
        *)
            echo "${0}: Error, unknown argument: ${argument}"
            usage
            exit 1
        ;;
    esac
done

NOW=$(echo "${NOW}" | grep -s '[0-9a-zA-Z._-]\+' -)
if [ -z "${NOW}" ]; then
    echo "Timestamp invalid, it must only contain letters, numbers, dots, and hyphens."
    exit 1
fi

command -v /opt/open-xchange/sbin/appsuiteui-history && /opt/open-xchange/sbin/appsuiteui-history -t $NOW

## cd ## || exit 0

if [ ! -f core ]; then
    echo "HTML files not found in $(pwd)" >&2
    exit 1
fi

VERSION=$(sed -n \
    's/^.*v=\([0-9a-zA-Z._-]\+\).*$/\1/p' \
    ui | head -n1 | cut -d . -f 1-3)

for f in ui core signin boot.js; do
    sed -i "s/${VERSION}"'\.[0-9a-zA-Z._-]\+/'"${VERSION}.${NOW}/g" "$f"
done
