#!/bin/sh

# Download pre-built webpack for current git SHA from GitHub

# These are produced by .github/workflows/build-dist.yml for every PR and push.
# This is a lot faster than having to npm install and run webpack.

# Returns 0 when successful, 1 in case of an error, or 2 in case the cache
# entry couldn't be found (but might be available after waiting a bit longer).

GITHUB_REPO='cockpit-dist'
SUBDIR='dist'

export V="${V-0}"

set -eu
cd "$(realpath -m "$0"/../..)"
. tools/git-utils.sh

wait=''
rebase=''
while [ $# != 0 ] ; do
    case "$1" in
        --wait)
            wait=1;;
        --rebase)
            rebase=1;;
        *)
            echo "usage: $0 [--rebase] [--wait]" >&2
            exit 1
    esac
    shift
done

[ -n "${quiet}" ] || set -x

if [ -e dist ]; then
    echo "jumpstart: dist/ already exists, skipping" >&2
    exit 1
fi

if [ "${NODE_ENV-}" = "development" ]; then
    echo 'jumpstart: only works with production builds (NODE_ENV != development)' >&2
    exit 1
fi

if ! git diff --quiet -- ':^test' ':^packit.yaml' ':^.github'; then
    echo 'jumpstart: uncommitted local changes, skipping download' >&2
    exit 1
fi

tag="sha-$(git rev-parse HEAD)"
for try in $(seq 50 -1 0); do
    if fetch_to_cache tag "${tag}"; then
        break
    fi
    if [ -z "${wait}" -o "$try" = '0' ]; then
        echo "There is no cache entry ${tag}" >&2
        exit 1
    fi
    message WAIT 30s
    sleep 30s
done

if [ -n "${rebase}" ]; then
    if [ -n "$(git status --porcelain)" ]; then
        echo 'Refusing to rebase tree with local changes' >&2
        git status >&2
        exit 1
    fi
    merge_base="$(cat_from_cache "${tag}" merge-base)"
    # If we don't already have that commit, we'll need to go fetch it
    if ! git fsck --no-dangling --connectivity-only "${merge_base}"; then
        message FETCH ".  [${merge_base}]"
        git fetch --no-write-fetch-head origin "${merge_base}"
    fi
    git rebase -- "${merge_base}"
fi

target_tree="$(cat_from_cache "${tag}" tree)"
if [ "$(git rev-parse HEAD^{tree})" != "${target_tree}" ]; then
    if [ -n "${rebase-}" ]; then
        echo "Internal error: even after rebase, don't have the correct tree" >&2
        exit 1
    else
        echo "The current working tree needs to be rebased: try --rebase" >&2
        exit 1
    fi
fi

tools/node-modules make_package_lock_json
unpack_from_cache "${tag}"
