#!/bin/bash
# @copyright Copyright (c) OX Software GmbH, Germany <info@open-xchange.com>
# @license AGPL-3.0
#
# This code is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with OX App Suite. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
#
# Any use of the work other than as authorized under this license or copyright law is prohibited.
#

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
