#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2021 - 2026 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"
TARGET_FLAG_MUSL="--target=x86_64-unknown-linux-musl"
ttl_url='https://w3id.org/valueflows/ont/vf.ttl'

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

name="$(basename "$ttl_url" | sed -e 's/[.].*$//')"
orig="${name}_downloaded.ttl"
fmtd="${name}_formatted.ttl"

# Download the latest/stable, publicly available ValueFlows Ontology
wget \
	"$ttl_url" \
	-O "$orig"

# Format it
cp "$orig" "$fmtd"
cargo run -- \
	"$fmtd" \
	--force \
	--canonicalize \
	--no-sparql-syntax \
	--pred-order-preset owl \
	--subj-type-order-preset owl

# Visually compare it
meld "$orig" "$fmtd" &
