#!/bin/sh
# Fetch, verify, trim, patch and record a vendored source.
#
#   tools/vendor/fetch [source ...]      (default: every source in the manifest)
#
# Network is required. This is a maintainer script; it is never run during
# R CMD check. Afterwards `tools/vendor/verify` re-checks the result offline.
set -eu

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
cd "$ROOT"
MANIFEST=tools/vendor/manifest.tsv
. tools/vendor/common.sh

# Which files we keep from each upstream archive, as paths (or globs) relative
# to the archive root. Everything else -- examples, build systems, test
# suites, the command-line programs -- is dropped so the tarball stays small
# and the attack surface stays reviewable.
#
#   zstd  the library's common/, compress/ and decompress/ trees and the two
#         public headers. Not dictBuilder/, legacy/ (ZSTD_LEGACY_SUPPORT=0),
#         deprecated/ or dll/, and not decompress/huf_decompress_amd64.S
#         (ZSTD_DISABLE_ASM=1), nor zdict.h, which nothing compiled includes.
#         LICENSE is the BSD licence at the archive root; COPYING, the GPLv2
#         alternative, is not taken -- zukomp distributes zstd under BSD-3.
#   lz4   the block API (lz4.c), the frame API (lz4frame.c) and the two things
#         the frame API links against: the HC compressor (lz4hc.c), which
#         serves frame levels 3 and above, and xxHash (xxhash.c), which
#         computes the frame checksums. Not lz4file.c, which does file I/O.
keep_files() {
    case "$1" in
        miniz) echo "miniz.c miniz.h LICENSE" ;;
        zstd)  echo "LICENSE lib/zstd.h lib/zstd_errors.h" \
                    "lib/common/*.c lib/common/*.h" \
                    "lib/compress/*.c lib/compress/*.h" \
                    "lib/decompress/*.c lib/decompress/*.h" ;;
        lz4)   echo "lib/LICENSE lib/lz4.c lib/lz4.h lib/lz4frame.c" \
                    "lib/lz4frame.h lib/lz4hc.c lib/lz4hc.h" \
                    "lib/xxhash.c lib/xxhash.h" ;;
        *) echo "unknown source: $1" >&2; exit 1 ;;
    esac
}

# The leading directory dropped from each kept path, so that the upstream
# lib/ tree becomes src/vendor/<source>/ with its internal layout intact
# (zstd's sources include each other by relative path).
strip_prefix() {
    case "$1" in
        zstd|lz4) echo "lib/" ;;
        *) echo "" ;;
    esac
}

sources=${*:-$(awk 'NR > 1 { print $1 }' FS='\t' "$MANIFEST")}

for src in $sources; do
    tag=$(manifest_field "$src" tag)
    url=$(manifest_field "$src" archive)
    want=$(manifest_field "$src" archive_sha256)
    patches=$(manifest_field "$src" patches)

    printf '==> %s %s\n' "$src" "$tag"

    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    archive="$tmp/archive"

    printf '    fetching %s\n' "$url"
    curl -sSL --fail --max-time 120 -o "$archive" "$url"

    got=$(sha256_of "$archive")
    if [ "$got" != "$want" ]; then
        printf '    sha256 MISMATCH\n      expected %s\n      got      %s\n' \
            "$want" "$got" >&2
        exit 1
    fi
    printf '    sha256 ok %s\n' "$got"

    mkdir -p "$tmp/x"
    case "$url" in
        *.zip) unzip -q -o "$archive" -d "$tmp/x" ;;
        *.tar.gz|*.tgz) tar -xzf "$archive" -C "$tmp/x" --strip-components=1 ;;
        *) echo "    unknown archive type: $url" >&2; exit 1 ;;
    esac

    dest="src/vendor/$src"
    rm -rf "$dest"
    mkdir -p "$dest"
    prefix=$(strip_prefix "$src")
    # Expanded inside the extracted tree, so the globs above match upstream's
    # files and nothing of ours.
    kept=$(cd "$tmp/x" && for f in $(keep_files "$src"); do
               [ -f "$f" ] || { echo "missing upstream file: $f" >&2; exit 1; }
               printf '%s\n' "$f"
           done) || exit 1
    for f in $kept; do
        rel=${f#"$prefix"}
        mkdir -p "$(dirname "$dest/$rel")"
        cp "$tmp/x/$f" "$dest/$rel"
        printf '    kept %s\n' "$rel"
    done

    if [ "$patches" != "-" ] && [ -n "$patches" ]; then
        for p in $(echo "$patches" | tr ',' ' '); do
            printf '    applying %s\n' "$p"
            patch -s -p1 -d "$dest" < "tools/patches/$src/$p"
        done
        # A hunk applied at an offset leaves FILE.orig behind (BSD patch
        # does so silently, and portably there is no flag to stop it).
        # record would then checksum it as a vendored file, and a global
        # *.orig gitignore keeps it out of the commit, so verify fails on
        # CI with "missing vendored file" for a tree that looks clean.
        find "$dest" \( -name '*.orig' -o -name '*.rej' \) -exec rm -f {} +
    fi

    rm -rf "$tmp"
    trap - EXIT
done

printf '==> recording checksums\n'
"$ROOT/tools/vendor/record"
printf 'done. review the diff under src/vendor/ before committing.\n'
