#!/bin/sh
# bldr - build a binary package from an Everest package file

pkgs=("${@}")

usage() {
	printf "${0} - Build a binary package from an Everest package file\n"
	printf "usage: ${0} [-h] [-v] [-b] PACKAGE\n"
	printf "\n"
	printf "${0} {-h --help}	Show this message\n"
	printf "${0} {-v --version}	Show the current version\n"
	printf "${0} {-b --build}	Build specified packages\n"
	printf "\n"
	printf "bldr is free software.\n"
	printf "See the GNU GPL version 3 for details.\n"
}

usage_small() {
	printf "usage: ${0} [-h] [-v] [-b] PACKAGE\n"
}

load_config() {
	if [ -f "/etc/bldr.conf" ]; then
		source /etc/bldr.conf
	elif [ -f "${HOME}/.config/bldr.conf" ]; then
		source ${HOME}/.config/bldr.conf
	elif [ -f "$(pwd)/bldr.conf" ]; then
		source $(pwd)/bldr.conf
	else
		printf "No valid bldr.conf found\n"
		printf "Valid files are:\n"
		printf "/etc/bldr.conf\n"
		printf "${HOME}/.config/bldr.conf\n"
		printf "$(pwd)/bldr.conf\n"
		exit 1
	fi
}

check_for_toolchain() {
	if [ -d "${TOOLCHAIN_PATH}" ]; then
		printf "Toolchain found, adding to temporary PATH...\n"
		PATH=${PATH}:${TOOLCHAIN_PATH}/bin
	else
		printf "Toolchain not found. Use the following command to download:\n"
		printf "curl -O -J https://musl.cc/$(uname -m)-linux-musl-cross.tgz\n"
		exit 1
	fi
}

check_if_input_is_blank() {
	if [[ "${@}" == "" ]]; then
		printf "No package(s) specified.\n"
		exit 1
	fi
}

get_pkg_sources() {
	pkgs=("${@}")
	for p in $pkgs; do
		source ${p}
		getsource
	done
}

mkpkg() {
	pkgs=("${@}")
	for p in $pkgs; do
		source ${p}
		buildpkg
		installpkg
	done
}

clean_after_failed() {
	printf "${0} failed to build packages.\n"
	printf "exiting...\n"
	cd .. && rm -rf /tmp/bldr-workspace
	exit 1
}

case $1 in
	-h|--help)
		usage "$@"
		exit 0
	;;
	-v|--version)
		printf "bldr v1.0.0\n"
		printf "everest-build-tools v1.0.0\n"
		exit 0
	;;
	-b|--build)
		load_config "$@"
		check_for_toolchain "$@"
		if [ "$?" != 0 ]; then
			exit 1
		fi
		shift
		check_if_input_is_blank "$@"
		mkdir /tmp/bldr-workspace
		cd /tmp/bldr-workspace
		get_pkg_sources "$@"
		pwd
		if [ "$?" != 0 ]; then
			clean_after_failed "$@"
			exit 1
		fi
		mkpkg "$@"
		if [ "$?" != 0 ]; then
			clean_after_failed "$@"
			exit 1
		fi
		printf "Finished.\n"
		exit 0
	;;
	*)
		usage_small "$@"
		exit 1
esac

usage_small "$@"
exit 1
