#!/bin/sh

if [ "$#" -lt 4 ]; then
    echo "Usage:"
    echo "  sha256-tarball-to SHA256 http://FETCH/FROM.tar.gz SRC1 DST1 [SRC2 DST2 [...]]"
    echo
    echo "SHA256 is the sha256sum of the tarball fetched; each SRC (which may be a"
    echo "directory) is expected to be a relative path into the unpacked tarball,"
    echo "and each DST is the absolute path it should be moved to."
    exit 1
fi

set -e
set -x

SHA256="$1"
URL="$2"
shift
shift

# Work in a tmpdir which we clean up at the end
tmpdir="$(mktemp -d)"
trap 'rm -r "$tmpdir"' EXIT
cd "$tmpdir"

# Fetch to a predictable name, not whatever curl guesses from the URL
LOCALFILE="archive.tar.gz"
curl -fL --retry 3 -o "$LOCALFILE" "$URL"

# Check the hash against what was passed in
echo "$SHA256  $LOCALFILE" >"$LOCALFILE.sha256"
sha256sum -c "$LOCALFILE.sha256"

tar xzf "$LOCALFILE"

# Take the rest of the arguments two-at-a-time, as source and
# destination to move out of the unpacked tarball.
while [ "$#" -gt 0 ]; do
    mv "$1" "$2"
    shift
    shift
done
