#!/bin/bash
set -euo pipefail
manifest=$1
output=$2
revision=$(jq -er .revision "$manifest")
origin=$(jq -er .origin "$manifest")
source_root="$output/libvfio-user-$revision"
mkdir -p "$source_root"
while IFS=$'\t' read -r relative_path expected; do
    case "$relative_path" in
        /*|*..*) echo "Invalid dependency path: $relative_path" >&2; exit 1 ;;
    esac
    destination="$source_root/$relative_path"
    mkdir -p "$(dirname "$destination")"
    if [[ -f "$destination" ]] && printf '%s  %s\n' "$expected" "$destination" | sha256sum --check --status; then
        continue
    fi
    curl --fail --silent --show-error --location --connect-timeout 20 --max-time 60 \
        "$origin$relative_path" -o "$destination.download"
    printf '%s  %s\n' "$expected" "$destination.download" | sha256sum --check --status
    mv "$destination.download" "$destination"
    if [[ $relative_path == *.sh ]]; then chmod 755 "$destination"; else chmod 644 "$destination"; fi
done < <(jq -r '.files | to_entries[] | [.key,.value] | @tsv' "$manifest")
tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \
    -C "$output" -czf "$output/libvfio-user.tar.gz" "libvfio-user-$revision"
(cd "$output" && sha256sum libvfio-user.tar.gz > libvfio-user.tar.gz.sha256)
echo "Exported verified libvfio-user $revision"
