#!/bin/sh

#----------------------------------------------------------------------
# Custom script for version 4 watch files (see "HISTORY AND UPGRADING"
# section of the uscan(1) manual).  This downloads the TinyMCE tarballs
# as secondary upstream tarballs and repacks according to d/copyright's
# Files-Excluded-component.
# Copyright © 2020 Guilhem Moulin <guilhem@debian.org>
# Dependencies: curl, jq
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#----------------------------------------------------------------------

set -ue
PATH="/usr/bin:/bin"
export PATH

if [ $# -ne 2 ] || [ "$1" != "--upstream-version" ]; then
    printf "Usage: %s --upstream-version version\\n" "$0" >&2
    exit 1
fi

for bin in curl jq; do
    if ! which "$bin" >/dev/null 2>&1; then
        printf "ERROR: \`%s\` is not in PATH\\n" "$bin" >&2
        exit 1
    fi
done

SOURCE_NAME="$(dpkg-parsechangelog -S Source)"
VERSION="$(dpkg-parsechangelog -S Version)"
UPSTREAM_VERSION="$2"
ORIGTARGZ=""

# see uupdate(1)
for t in gz bz2 lzma xz; do
    p="../roundcube_$UPSTREAM_VERSION.orig.tar.$t"
    if [ -f "$p" ]; then
        ORIGTARGZ="$p"
        break
    fi
done
if [ -z "$ORIGTARGZ" ]; then
    echo "Could not find orig tarball!" >&2
    exit 1
fi

TEMPDIR="$(mktemp --tmpdir --directory "$SOURCE_NAME-$UPSTREAM_VERSION.XXXXXXXX")"
trap 'rm -rf -- "TEMPDIR"' EXIT INT TERM

BASEDIR="$TEMPDIR"
tar -C "$BASEDIR" -xaf "$ORIGTARGZ" --strip-components=1 --wildcards "*/jsdeps.json"

get() {
    local component="$1" url="$2" ext="${2##*/}" destfile
    case "$ext" in
        *.tar.bz2) ext="tar.bz2";;
        *.tar.gz) ext="tar.gz";;
        *.tar.xz) ext="tar.xz";;
        *) ext="${ext##*.}";;
    esac
    destfile="$TEMPDIR/$component.$ext"
    curl -fS -Lso "$destfile" "$url"
    mk-origtargz -C "${USCAN_DESTDIR:-".."}" -c "$component" -v "$UPSTREAM_VERSION" --rename "$destfile"
}

TINYMCE_VERSION="$(jq -r ".dependencies | map(select (.lib == \"tinymce\")) [0].version" <"$BASEDIR/jsdeps.json")"

# we don't use .url from jsdeps.json as it doesn't contain the source
get "tinymce" "https://download.tiny.cloud/tinymce/community/tinymce_${TINYMCE_VERSION}_dev.zip"
get "tinymce-langs" "https://www.tiny.cloud/docs-4x/language/tinymce${TINYMCE_VERSION%%.*}x_languages.zip"
