#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
helper="$script_dir/lifecycle.py"
# Source-tree tests use the same engine as the installed package.
if [[ ! -f "$helper" ]]; then
    helper="$script_dir/../../../packaging/lifecycle/kait2en-lifecycle.py"
fi
args=()
if [[ -n "${T2_DSP_TEST_ROOT:-}" ]]; then args=(--root "$T2_DSP_TEST_ROOT"); fi
case "${1:-}" in
    configure) action=migrate ;;
    removed) action=remove ;;
    *) printf '[t2-dsp] invalid lifecycle action\n' >&2; exit 1 ;;
esac
if ! python3 "$helper" t2-dsp "$action" "${args[@]}"; then
    printf '[t2-dsp] migration/removal reported errors. Continuing package transaction.\n' >&2
    log_file="${T2_DSP_TEST_ROOT:-}/var/log/t2-dsp-install.log"
    if ! printf 'lifecycle %s reported errors\n' "$action" >>"$log_file"; then
        printf '[t2-dsp] error: cannot save lifecycle failure report\n' >&2
    fi
    if [[ -n "${KAIT2EN_INSTALL_ERRORS:-}" ]]; then
        if ! printf 't2-dsp: lifecycle %s reported errors\n' "$action" >>"$KAIT2EN_INSTALL_ERRORS"; then
            printf '[t2-dsp] error: cannot append installer failure report\n' >&2
        fi
    fi
fi
exit 0
