#!/bin/sh

set -eu
version="2.47.4"

command=$1
shift

case "${command}" in
    configure)
        upstream_dir=$1
        mkdir -p /usr/share/wine/gecko
        ln -fns "${upstream_dir}/wine-gecko-${version}-x86.msi" "/usr/share/wine/gecko/wine-gecko-${version}-x86.msi"
        ln -fns "${upstream_dir}/wine-gecko-${version}-x86_64.msi" "/usr/share/wine/gecko/wine-gecko-${version}-x86_64.msi"
    ;;
    unconfigure)
        rm -f "/usr/share/wine/mono/wine-gecko-${version}-x86.msi"
        rm -f "/usr/share/wine/mono/wine-gecko-${version}-x86_64.msi"
    ;;
    unpack)
        upstream_pack=$1
        upstream_dir=$2
        
        tar -x -f "$upstream_pack" -C "$upstream_dir"
    ;;
    download) #based on ubuntu-wallpapers-bullseye
        upstream_pack=$(readlink -f "$1")
        tmpdir=
        trap '[ -n "$tmpdir" ] && rm -rf "$tmpdir"' 0 INT TERM
        tmpdir=$(mktemp -d)

        (
        cd "$tmpdir"
        mkdir -p wine-gecko
        while read sha384 fwfilepath; do
            fwfile=$(basename "$fwfilepath")
            wget \
                --no-use-server-timestamps \
                --no-cookies \
                --output-document "$fwfile" \
                --progress=dot:mega \
                "${fwfilepath}" || {
                [ $? -eq 4 ] && exit 2 ## Network failure.
                exit 1
            }
            if ! echo "${sha384} $(basename $fwfilepath)" | sha384sum --check >/dev/null; then
            actual_checksum=$(sha384sum "$fwfile" | awk '{ print $1 }')
            echo "checksum NOT matching for $fwfilepath" >&2
            echo "expected: ${sha384} / actual: ${actual_checksum}" >&2
            exit 1
            fi
            mv "$fwfile" wine-gecko/ || exit 1
        done <<EOF
b7757916660ca6ced6fc7a342e66703dc53c293e07a3cbc6d6c641fdc1f5875aa290723c8055d86c00e1538a25bcf41c  http://dl.winehq.org/wine/wine-gecko/2.47.4/wine-gecko-2.47.4-x86_64.msi
cbab5929f04851c41aa3ee9e8e82b87fdf261f6ce64b6eadf8de59bd42ba687dfaad9100d43199d7b3861cfa1e1e4e22  http://dl.winehq.org/wine/wine-gecko/2.47.4/wine-gecko-2.47.4-x86.msi
EOF

        # Set LC_COLLATE=C so that files always sort in the same
        # way (so we get the same tar-archive independent of locales).
        env LC_COLLATE=C \
            tar -C wine-gecko --mtime='2000-01-01 00:00:00 +00:00' --sort=name -c \
            -f "$upstream_pack" .
        )
    ;;

    *)
    ;;
esac
