#!/bin/bash

# this scripts compiles bffh for all target architectures which are defined in Cross.toml (using cross_rs). 
# We use cross_rs because it supports easy and successful cross compilation for different architectures with less efforts
# For this we install podman by default

# requirements
# - this script only runs on debianoid OS (Debian, Ubuntu, Kubuntu, ... having dpkg)

git branch

# init submodules, if not done yet. running multiple times does not matter
git submodule update --init --recursive

# pull latest stuff from submodules
git pull --recurse-submodules

echo -e "\n+++++++++++++++++++++++++++++++++++++++++++"
echo -e "installing requirements ..."
echo -e "+++++++++++++++++++++++++++++++++++++++++++\n"

sudo apt install podman gsasl libgsasl7-dev libssl-dev libclang-dev cmake clang capnproto mosquitto mosquitto-clients build-essential libpcsclite-dev

if ! command -v rustup 2>&1 >/dev/null
then
	echo -e "Istalling rustup with stable rust + cargo..."
	curl https://sh.rustup.rs -sSf | sh
	echo 'source "$HOME/.cargo/env"' >> ~/.bashrc
	source ~/.bashrc
	rustup install stable
	rustup default stable
	echo -e "rustup installed:"
	rustc +stable --version
	cargo +stable --version
else
	echo -e "rustup found:"
	rustc +stable --version
	cargo +stable --version
	echo -e "rustup: updating ..."
	rustup update
fi

echo -e "Installing cross-rs ..."
cargo install cross

echo -e "\n+++++++++++++++++++++++++++++++++++++++++++"
echo -e "gathering some general info ..."
echo -e "+++++++++++++++++++++++++++++++++++++++++++\n"
DEB_HOST_ARCH_CPU=$(dpkg-architecture | grep DEB_HOST_ARCH_CPU)
DEB_HOST_MULTIARCH=$(dpkg-architecture | grep DEB_HOST_MULTIARCH)

if [[ ! $DEB_HOST_ARCH_CPU -eq "amd64" ]]; then
	echo -e "Host architecture is not amd64. Aborting ..."
	exit 1
fi

# this generates bffhd and fabfire_provision binary files in target/<architecture>/ dir
# we compile for amd64 (x86_64) using native "cargo build --release". Other architectures we use podman + cross_rs
echo -e "\n+++++++++++++++++++++++++++++++++++++++++++"
echo -e "cross-compiling ..."
echo -e "+++++++++++++++++++++++++++++++++++++++++++\n"
#build bffhd binaries
time cargo build --release --target-dir target/x86_64-unknown-linux-gnu
time cross build --target=aarch64-unknown-linux-gnu --release
time cross build --target=armv7-unknown-linux-gnueabihf --release

#build fabfire_provision binaries
cd fabfire_provision/
time cargo build --release --target-dir ../target/x86_64-unknown-linux-gnu
time cross build --target=aarch64-unknown-linux-gnu --release
time cross build --target=armv7-unknown-linux-gnueabihf --release
cd ../