#!/bin/bash

# Created by argbash-init v2.10.0
# ARG_POSITIONAL_SINGLE([ref],[Git commit, tag, or branch],[HEAD])
# ARGBASH_SET_DELIM([ ])
# ARG_OPTION_STACKING([getopt])
# ARG_RESTRICT_VALUES([none])
# ARG_DEFAULTS_POS([])
# ARG_HELP([Update librtas and librtasevent ABI definitions.],[Generates ABI definitions as of the given Git commit. Uses Podman \nand a temporary Git worktree. Harmful ABI changes can be detected\nusing the 'abi-check' build target.])
# ARGBASH_GO()
# needed because of Argbash --> m4_ignore([
### START OF CODE GENERATED BY Argbash v2.10.0 one line above ###
# Argbash is a bash code generator used to get arguments parsing right.
# Argbash is FREE SOFTWARE, see https://argbash.io for more info


die()
{
	local _ret="${2:-1}"
	test "${_PRINT_HELP:-no}" = yes && print_help >&2
	echo "$1" >&2
	exit "${_ret}"
}


begins_with_short_option()
{
	local first_option all_short_options='h'
	first_option="${1:0:1}"
	test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}

# THE DEFAULTS INITIALIZATION - POSITIONALS
_positionals=()
_arg_ref="HEAD"
# THE DEFAULTS INITIALIZATION - OPTIONALS


print_help()
{
	printf '%s\n' "Update librtas and librtasevent ABI definitions."
	printf 'Usage: %s [-h|--help] [<ref>]\n' "$0"
	printf '\t%s\n' "<ref>: Git commit, tag, or branch (default: 'HEAD')"
	printf '\t%s\n' "-h, --help: Prints help"
	printf '\n%s\n' "Generates ABI definitions as of the given Git commit. Uses Podman
and a temporary Git worktree. Harmful ABI changes can be detected
using the 'abi-check' build target."
}


parse_commandline()
{
	_positionals_count=0
	while test $# -gt 0
	do
		_key="$1"
		case "$_key" in
			-h|--help)
				print_help
				exit 0
				;;
			-h*)
				print_help
				exit 0
				;;
			*)
				_last_positional="$1"
				_positionals+=("$_last_positional")
				_positionals_count=$((_positionals_count + 1))
				;;
		esac
		shift
	done
}


handle_passed_args_count()
{
	test "${_positionals_count}" -le 1 || _PRINT_HELP=yes die "FATAL ERROR: There were spurious positional arguments --- we expect between 0 and 1, but got ${_positionals_count} (the last one was: '${_last_positional}')." 1
}


assign_positional_args()
{
	local _positional_name _shift_for=$1
	_positional_names="_arg_ref "

	shift "$_shift_for"
	for _positional_name in ${_positional_names}
	do
		test $# -gt 0 || break
		eval "$_positional_name=\${1}" || die "Error during argument parsing, possibly an Argbash bug." 1
		shift
	done
}

parse_commandline "$@"
handle_passed_args_count
assign_positional_args 1 "${_positionals[@]}"

# OTHER STUFF GENERATED BY Argbash

### END OF CODE GENERATED BY Argbash (sortof) ### ])
# [ <-- needed because of Argbash


# vvv  PLACE YOUR CODE HERE  vvv
# For example:
set -eu
set -o pipefail

worktree_dir="$(mktemp -t --directory librtas-abi.XXXXXX)"
orig_dir="$PWD"
abi_dir="data/abixml"

cleanup() {
    set +e
    echo "Cleaning up worktree ${worktree_dir}"
    test -d "$worktree_dir" && cd "$worktree_dir" && git clean -xdf
    cd "$orig_dir" && git worktree remove "$worktree_dir"
    test -d "$worktree_dir" && rm -r "$worktree_dir"
}

trap cleanup EXIT

git worktree add --detach --checkout "$worktree_dir" "$_arg_ref"

declare -a runc_opts
runc_opts=(
    --interactive
    --log-driver none
    --rm
    --security-opt label=disable
    --volume "${worktree_dir}":/source:rw
    --workdir /source
)

cat <<"EOF" |
set -eux

declare -a pkgs
pkgs=(
    abigail-tools
    autoconf
    automake
    gcc-powerpc-linux-gnu
    gcc-powerpc64-linux-gnu
    gcc-powerpc64le-linux-gnu
    libc6-dev-powerpc-cross
    libc6-dev-ppc64-cross
    libc6-dev-ppc64el-cross
    libtool
    make
)

apt-get update
apt-get -y --purge dist-upgrade
apt-get install -y --no-install-recommends "${pkgs[@]}"

abi_dir="data/abixml"

./autogen.sh

for cc in \
    powerpc-linux-gnu-gcc \
    powerpc64-linux-gnu-gcc \
    powerpc64le-linux-gnu-gcc \
    ; do

    declare -a cflags
    cflags=(
        -O2
        -Wall
        -gdwarf-5
        -std=gnu99
    )
    host="$($cc -dumpmachine)"

    ./configure --host="${host}" CC="$cc" CFLAGS='-O2 -g -std=gnu99'
    make -j "$(nproc)" V=1

    for lib in librtas librtasevent ; do
        mkdir -p "${abi_dir}/${lib}"
        declare -a abidw_opts
        abidw_opts=(
            --annotate
            --drop-private-types
            --drop-undefined-syms
            --no-corpus-path
            --no-show-locs
            --type-id-style hash
        )
        case "$lib" in
            librtas)
                abidw_opts+=(
                    --header-file librtas_src/librtas.h
                )
                ;;
            librtasevent)
                abidw_opts+=(
                    --header-file librtasevent_src/librtasevent.h
                    --header-file librtasevent_src/librtasevent_v4.h
                    --header-file librtasevent_src/librtasevent_v6.h
                )
                ;;
        esac
        abidw "${abidw_opts[@]}" --out-file "${abi_dir}/${lib}/${host}.xml" ".libs/${lib}.so"
    done
    make distclean
done
EOF
podman run "${runc_opts[@]}" debian:bookworm

cp -r "${worktree_dir}/${abi_dir}"/librtas/ "$abi_dir"/
cp -r "${worktree_dir}/${abi_dir}"/librtasevent/ "$abi_dir"/
if git diff --quiet -- "$abi_dir"; then
    echo "ABI definitions unchanged."
else
    echo "ABI definitions changed, please review:"
    git diff --stat -- "$abi_dir"
fi

# ^^^  TERMINATE YOUR CODE BEFORE THE BOTTOM ARGBASH MARKER  ^^^

# ] <-- needed because of Argbash
