#!/bin/bash
# sudo apt install crossbuild-essential-{i386,armel,armhf,arm64,mipsel,mips64el}
set -e
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"

function mk_musl() {
	local outdir="/usr/local/musl/${1}"
	local build="musl-build-${1}"
	rm -rf "${build}" && mkdir -p "${build}"
	tar -xvf "musl-latest.tar.gz" --strip-components=1 -C "${build}"
	pushd "${build}"
	local optdirs="$(find './src' -mindepth 1 -maxdepth 1 -type d -printf '%f,' | sed 's/,$//g')"
	if [ -z "${2}" ]; then
		./configure --enable-optimize="${optdirs}" --disable-shared --prefix="${outdir}"
	else
		./configure --enable-optimize="${optdirs}" --disable-shared --prefix="${outdir}" --host="${2}"
	fi
	make
	sudo rm -rf "${outdir}"
	sudo make install
	popd
}

if [ "$(gcc -dumpmachine)" != "x86_64-linux-gnu" ]; then
	echo "This script is supposed to run on the native \"x86_64-linux-gnu\" platform !!!"
	exit 1
fi

curl -vkf -o "musl-latest.tar.gz" "https://musl.libc.org/releases/musl-latest.tar.gz"

mk_musl x86_64
mk_musl i686 i686-linux-gnu
mk_musl armel arm-linux-gnueabi
mk_musl armhf arm-linux-gnueabihf
mk_musl arm64 aarch64-linux-gnu
mk_musl mipsel mipsel-linux-gnu
mk_musl mips64el mips64el-linux-gnuabi64
