#! /bin/sh

# This file is part of IVRE.
# Copyright 2011 - 2026 Pierre LALET <pierre@droids-corp.org>
#
# IVRE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IVRE is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IVRE. If not, see <http://www.gnu.org/licenses/>.

# Regenerates bash_completion/ivre from the argparse parsers
# (ivre.cli:get_parser) using shtab. Requires the [completion] and
# [plots] extras (importing ivre.tools.plotdb needs matplotlib).
#
# The parsers reflect the configured DB backends and the installed
# optional dependencies (e.g. dbus-python adds a choice to the
# --graph options), so the output must be generated in a clean
# environment to match the CI regen check: no custom IVRE
# configuration and no extras beyond [completion] and [plots]. The
# canonical invocation is:
#
#     uv run --with-editable '.[completion,plots]' --no-project \
#         --python 3.13 ./pkg/buildcompletion

cd "$(dirname "$0")/.." || exit 255

for conf in /etc/ivre.conf /etc/ivre/ivre.conf /usr/local/etc/ivre.conf \
    /usr/local/etc/ivre/ivre.conf "$HOME/.ivre.conf" "$IVRE_CONF"; do
    if [ -n "$conf" ] && [ -f "$conf" ]; then
        printf 'WARNING: %s exists; the generated completions may differ from the CI regen check.\n' "$conf" >&2
    fi
done

tmp="bash_completion/.ivre.tmp"
raw="bash_completion/.ivre.raw.tmp"
# shtab is run to a temporary file first so its exit status (e.g.
# --error-unimportable failures) is still what decides success; the
# sed expression then strips shtab's own leading header block (the
# "AUTOMATICALLY GENERATED by ..." comment and, depending on the
# shtab version, usage instructions): its wording changes across
# shtab releases and would make the regen check fail on a shtab
# upgrade even when the completions themselves are unchanged. It
# deletes everything before the first line that is neither a comment
# nor blank; later comments (inside the generated functions) are
# kept.
if python -m shtab --shell=bash --error-unimportable --prog ivre \
    ivre.cli.get_parser > "$raw"; then
    {
        printf '# Generated by pkg/buildcompletion -- do not edit by hand.\n'
        sed '/^[^#]/,$!d' "$raw"
    } > "$tmp"
    rm -f "$raw"
    mv "$tmp" bash_completion/ivre
else
    rm -f "$raw" "$tmp"
    exit 1
fi
