#!/bin/bash

set -u           # exit if any referenced variable has not been previously defined.
set -e           # exit if any command has a non-zero exit code.
set +o pipefail  # do not exit if a command fails inside a pipe.
unset CDPATH
IFS=$' \n\t'
: "${BASH_SOURCE?'BASH_SOURCE variable not defined, not running in bash?'}"

THIS_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"

# change into the directory this script resides in
cd "$THIS_DIR"

#set -x

VERSION=$(git tag --list --points-at HEAD)
if [[ -z "$VERSION" ]]; then
    >&2 echo "Error: git head is not tagged."
    exit 1
fi

cargo build --release

TARGET_DIR=$(realpath ../target)

find "$TARGET_DIR" -mindepth 1 -maxdepth 1 -type d \
    '(' -name 'aarch*' -o -name 'arm*' -o -name 'x86*' ')' -printf '%f\n' | \
while read -r TARGET ; do
    ARCH=$(cut -d - -f 1 <<< "$TARGET")
    OS=$(cut -d - -f 3 <<< "$TARGET")

    if [[ "$OS" = windows ]]; then
        EXEC_SUFFIX='.exe'
    else
        EXEC_SUFFIX=''
    fi

    ARCHIVE="$TARGET_DIR/release/binary-security-check-${VERSION}-${ARCH}-${OS}.tar.xz"

    echo "binary-security-check-${VERSION}-${ARCH}-${OS}.tar.xz"

    tar cJf "$ARCHIVE" -C "$TARGET_DIR/$TARGET/release" "binary-security-check${EXEC_SUFFIX}" &
done

wait
