#!/usr/bin/env bash
set -euo pipefail

this_file=$(readlink -f "${BASH_SOURCE[0]}")
this_dir=${this_file%/*}
. "${this_dir}"/lib.bash

# Export SOURCE_DATE_EPOCH, computing from Git, if not already present.
#
# This means that if some higher-level build script wants to set this
# variable, we'll follow its choice; otherwise, we use the commit date
# of the current Git commit.
#
# See: https://reproducible-builds.org/docs/source-date-epoch/
export_source_date_epoch() {
    : "${SOURCE_DATE_EPOCH:=$(git log -1 --format=%ct)}"
    export SOURCE_DATE_EPOCH
}

# Like `tar -czf`, but with more-reproducible output.
tar_czf_reproducibly() {
    local outfile="$1"
    shift

    export_source_date_epoch

    # For this formidable set of `tar` options, see:
    #   https://reproducible-builds.org/docs/archives/
    tar --sort=name --mtime="@${SOURCE_DATE_EPOCH}" \
        --owner=0 --group=0 --numeric-owner \
        --pax-option=exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime \
        -c "$@" \
      | gzip -n >"${outfile}"
}

archive() {
    local slug_target="$1" target_dir="$2"
    local version slug tmpdir staging outdir artifact

    version=$(get_version)
    slug="toml-${version}-${slug_target}"

    tmpdir=$(mktemp -d)
    staging="${tmpdir}/${slug}"
    mkdir -p "${staging}"
    cp {README.md,LICENSE,CHANGELOG.md} "${staging}"/
    cp "${target_dir}"/release/toml "${staging}"/

    outdir=target/archive
    artifact="${outdir}"/"${slug}".tar.gz
    mkdir -p "${outdir}"
    tar_czf_reproducibly "${artifact}" -C "${tmpdir}" "${slug}"
    echo "${artifact}"
}

# Build (a tarball containing) a statically-linked binary for Linux.
build_linux_x86() {
    local rust_target=x86_64-unknown-linux-musl
    local target_dir=target/"${rust_target}"

    export_source_date_epoch

    cross build --verbose --release --target "${rust_target}"
    strip "${target_dir}"/release/toml

    # Call the artifact "toml-0.M.N-x86_64-linux.tar.gz" rather than
    # a more puzzling-looking name with "unknown" and "musl".
    archive x86_64-linux "${target_dir}"
}

(( $# == 1 )) || die "usage: tools/build-release TARGET"
opt_target="$1"

case "${opt_target}" in
    linux-x86) build_linux_x86;;
    # linux-arm)  # TODO
    # macos)      # TODO
    # archive) archive "$@";;  # perhaps add for use developing this script
    *) die "unknown target: ${opt_target}";;
esac
