#!/bin/bash
#   ▄████████▄      +        ███ +  ▄█████████ ███     +
#  ███▀    ▀███ +         +  ███    ███▀  +    ███ +       +
#  ███  +   ███ ███   ███ █████████ ███        ███  ███   ███
#  ███     +███ ███   ███    ███    ███▐██████ ███  ███   ███
#  ███ +    ███ ███+  ███   +███    ███     +  ███  ███ + ███
#  ███▄    ▄███ ███▄  ███    ███ +  ███  +     ███  ███▄  ███
#   ▀████████▀ + ▀███████    ███▄   ███▄       ▀████ ▀███████
#       +                  +                +             ███
#  +   ▀████████████████████████████████████████████████████▀
#
# A script to package release binaries + README.md into zip files.
# Usage: cd outfly; build/pack.sh [-b]
# Options: -b: cross-compile targets before packing

set -e

function check_uncommitted_assets() {
    ( cd assets; [ $(git status --porcelain . | wc -l) -gt 0 ] )
}

if check_uncommitted_assets; then
    echo "Please make sure there are no uncommited files in the 'asset' directory before packing"
    exit 1
fi

if [ "$1" == "-b" ]; then
    cargo build --release --target=x86_64-unknown-linux-gnu --no-default-features --features release_linux
    cargo build --release --target=x86_64-pc-windows-gnu --no-default-features --features release_windows
fi

VERSION="$(sed -nr 's/^\s*version\s*=\s*"(.*)"\s*$/\1/p' Cargo.toml | head -n1)"
test -z "$VERSION" && echo 'Error: Could not extract version from Cargo.toml' && exit
echo "Extracted version from Cargo.toml: $VERSION"

TMPPATH=ZIP_TMP_PATH
mkdir "$TMPPATH"
cd "$TMPPATH"

SRCPATH="outfly_v$VERSION"
mkdir "$SRCPATH"

cp ../README.md "$SRCPATH"
cp ../LICENSE.md "$SRCPATH"
cp ../CHANGELOG.md "$SRCPATH"
cp ../target/x86_64-pc-windows-gnu/release/outfly.exe "$SRCPATH"/OutFly.exe
zip -v -r -9 ../"outfly_v${VERSION}_windows.zip" "$SRCPATH"

rm "$SRCPATH"/OutFly.exe
cp ../target/x86_64-unknown-linux-gnu/release/outfly "$SRCPATH"
zip -v -r -9 ../"outfly_v${VERSION}_linux.zip" "$SRCPATH"

cd ..
rm -rf "$TMPPATH"