#!/bin/sh
# Packs this repository's committed history for stepmaniay.com, where anyone can clone it with
# plain git over HTTPS: a bare copy in one pack with the files a client reads first (info/refs,
# objects/info/packs), a source tarball for anyone without git, and release.json naming the commit,
# the tarball's SHA-256 and the latest results. One archive, for the server's
# `manage.py verification_publish`.
#
# tools/publish.sh <archive.tar>
set -eu
KIT=$(cd "$(dirname "$0")/.." && pwd)
OUT=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
[ -z "$(git -C "$KIT" status --porcelain)" ] || { echo "commit first: what's published is the committed history" >&2; exit 1; }
git clone -q --bare --no-local "$KIT" "$WORK/bare.git"
git -C "$WORK/bare.git" repack -q -a -d -f
git -C "$WORK/bare.git" update-server-info
mkdir -p "$WORK/out/repo/info" "$WORK/out/repo/objects/info" "$WORK/out/repo/objects/pack"
cp "$WORK/bare.git/HEAD" "$WORK/out/repo/HEAD"
cp "$WORK/bare.git/info/refs" "$WORK/out/repo/info/refs"
cp "$WORK/bare.git/objects/info/packs" "$WORK/out/repo/objects/info/packs"
cp "$WORK/bare.git"/objects/pack/pack-*.pack "$WORK/bare.git"/objects/pack/pack-*.idx "$WORK/out/repo/objects/pack/"
COMMIT=$(git -C "$KIT" rev-parse HEAD)
TARBALL=stepmaniay-verification-$(git -C "$KIT" rev-parse --short=12 HEAD).tar.gz
git -C "$KIT" archive --format=tar.gz --prefix=stepmaniay-verification/ -o "$WORK/out/$TARBALL" HEAD
# Each test's latest results folder.
LATEST=$(for t in "$KIT"/tests/*/; do ls -d "$KIT/results/$(basename "$t")"-* 2>/dev/null | sort | tail -n 1; done)
# shellcheck disable=SC2086
python3 "$KIT/tools/release.py" "$COMMIT" "$WORK/out/$TARBALL" $LATEST > "$WORK/out/release.json"
# COPYFILE_DISABLE keeps macOS from adding its ._ metadata files beside each one.
COPYFILE_DISABLE=1 tar -cf "$OUT" -C "$WORK/out" .
echo "$OUT: commit $COMMIT, $(du -h "$OUT" | cut -f1)"