#!/bin/bash

set -e

# either "emu_release_tarball" or "emuv4_release_tarball"
base=$(basename $0 .sh)

if [ -z ${BUILD_WORKSPACE_DIRECTORY+x} ]; then
    bazel run -- "//firmware/tools/scripts:$base" "$@"
    exit $?
fi

for elf in $(find -name '*.elf'); do
    if [ "$(head -c 4 "${elf}")" != "$(echo -en \\x7fELF)" ]; then
        echo -e '\e[0;31mThe built application executables are not valid ELF files.\e[0m'
        echo 'One common cause of this is stubbed out QNX build. Check your QNX SDP setup and add `export ZOOX_ENABLE_QNX70=1` to your environment.'
        exit 1
    fi
done

if [ $# -ne 1 -o "$1" = --help ]; then
    echo "Usage: $base [output SFX archive]"
    echo "This script packs the runtime environment of emu_deploy_all into a SFX archive."
    exit 1
else
    if [ ${1::1} = / ]; then
        OUTPUT="$1"
    else
        OUTPUT="$BUILD_WORKING_DIRECTORY/$1"
    fi
fi

# Use a balance between compressed size and compression time with `xz -1`
# Static mtime so that tarball hash is deterministic
XZ_OPT=-1 tar --xz --dereference --create --mtime='1970-01-01' --owner=nobody --group=nobody ..|cat "firmware/tools/scripts/$base.template" - > "$OUTPUT"

chmod +x "$OUTPUT"
