#!/bin/bash
# Create the additional orig tarball from a reviewed MAVLink commit.
set -euo pipefail

if [[ $# -lt 3 || $# -gt 4 ]]; then
    echo "Usage: $0 UPSTREAM_VERSION MAVLINK_REPOSITORY FULL_COMMIT [OUTPUT_DIRECTORY]" >&2
    exit 2
fi

version=$1
repository=$2
commit=$3
output_directory=${4:-..}

# These values also become parts of the archive's filename and prefix.
if [[ ! $version =~ ^[0-9][A-Za-z0-9.+~]*$ ]]; then
    echo "Expected an upstream version without an epoch or Debian revision" >&2
    exit 2
fi
if [[ ! $commit =~ ^[0-9a-f]{40}$ ]]; then
    echo "Expected a full, lowercase, 40-character MAVLink commit SHA" >&2
    exit 2
fi
git -C "$repository" cat-file -e "$commit^{commit}"
git -C "$repository" cat-file -e "$commit:COPYING"
git -C "$repository" cat-file -e "$commit:message_definitions/v1.0/common.xml"

output="$output_directory/python-pymavlink_${version}.orig-mavlink.tar.xz"
if [[ -e $output || -L $output ]]; then
    echo "Refusing to overwrite $output; use pristine-tar for an existing release" >&2
    exit 1
fi

temporary=$(mktemp "$output_directory/.mavlink-orig.XXXXXX")
trap 'rm -f -- "$temporary"' EXIT
git -C "$repository" archive --format=tar --prefix="mavlink-$commit/" \
    "$commit" -- COPYING message_definitions |
    env -u XZ_OPT -u XZ_DEFAULTS xz -6 --threads=1 > "$temporary"
chmod 644 "$temporary"
# Publish only the finished archive, without replacing an existing file.
ln -- "$temporary" "$output"
echo "$output"
