#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2022 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

# initial default values
APP_NAME="STOML installer"
loc_tools_dir="target/tools"
loc_stoml_path="$loc_tools_dir/stoml"
stoml_version="${STOML_VERSION:-${1:-0.7.0}}"
stoml_gh_slug="freshautomations/stoml"
stoml_dl_url="https://github.com/$stoml_gh_slug/releases/download/v$stoml_version/stoml_linux_amd64"

function print_help() {

	local script_name="$(basename "$0")"
	echo "$APP_NAME - Installs the simple shell TOML parser STOML"
	echo "in '$loc_tools_dir' -> No meddling with your system, not even PATH."
	echo "This set of scripts uses STOML to parse Rust"
	echo "project description files ('Cargo.toml')."
	echo
	echo "Usage:"
	echo "  $script_name [OPTION...]"
	echo "Options:"
	echo "  -h, --help"
	echo "    Show this help message and exit"
	echo "Examples:"
	echo "  $script_name"
	echo "  $script_name --help"
}

# 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
			;;
		*) # non-/unknown option
			POSITIONAL+=("$arg") # save it in an array for later
			;;
	esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if ! which stoml
then
	echo "Install STOML (BASH TOML parser) v$stoml_version ..."
	mkdir -p "$loc_tools_dir"
	curl "$stoml_dl_url" \
		--fail \
		--location \
		--output "$loc_stoml_path"
	chmod +x "$loc_stoml_path"
	# This we need only for within this script
	PATH="$PATH:$loc_tools_dir"
	# As the above "which stoml" did not output anything,
	# we show the path now
	echo "$loc_stoml_path"
fi

stoml --version
