#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2021 - 2023 Robin Vobruba <hoijui.quaero@gmail.com>
#
# SPDX-License-Identifier: Unlicense

# Exit immediately on each error and unset variable;
# see: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -Eeuo pipefail
#set -Eeu

script_dir=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
# shellcheck source=./env
source "$script_dir/env"

# initial default values
APP_NAME="Rust project build script"
musl=true
strip=true

function print_help() {

	local script_name="$(basename "$0")"
	echo "$APP_NAME - Simply builds the current project."
	echo "By default, it tries to create a MUSL build,"
	echo "which is compatible with all Linux 64bit systems."
	echo "NOTE: This script depends on the 'env' script in the same directory."
	echo
	echo "Usage:"
	echo "  $script_name [OPTION...]"
	echo "Options:"
	echo "  -h, --help"
	echo "    Show this help message and exit"
	echo "  --skip-musl"
	echo "    Do not build for MUSL, but for the native target"
	echo "  --skip-strip"
	echo "    Do not strip the debug-symbols from the resulting binary"
	echo "Examples:"
	echo "  $script_name"
	echo "  $script_name --skip-musl"
}

# read command-line args
POSITIONAL=()
while [[ $# -gt 0 ]]
do
	arg="$1"
	shift # $2 -> $1, $3 -> $2, ...

	case "$arg" in
		-h|--help)
			print_help
			exit 0
			;;
		--skip-musl)
			musl=false
			;;
		--skip-strip)
			strip=false
			;;
		*) # non-/unknown option
			POSITIONAL+=("$arg") # save it in an array for later
			;;
	esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

uname_out="$(uname -s)"
case "$uname_out" in
	Linux*)
		linux=true;;
	*)
		linux=false
esac

if $linux && $musl
then
	if [ -z "${TARGET_FLAG:-}" ]
	then
		TARGET_FLAG="--target=x86_64-unknown-linux-musl"
	else
		>&2 echo "\
ERROR: Trying to set target to MUSL (--skip-musl was not given), \
but TARGET_FLAG is already set!"
		exit 3
	fi
fi

CARGO_FLAGS=()
if [ -n "$TARGET_FLAG" ]
then
	CARGO_FLAGS+=("$TARGET_FLAG")
fi
$CARGO build --verbose --release "${CARGO_FLAGS[@]}"

if $strip
then
	if [ -f "$BINARY_PATH_MUSL" ]
	then
		strip "$BINARY_PATH_MUSL"
	fi
	if [ -f "$BINARY_PATH" ]
	then
		strip "$BINARY_PATH"
	fi
fi
