#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2015-2016, 2026 InterGenJLU
#
# bottom 0.12.3 — cross-platform graphical process/system monitor
# Upstream: https://github.com/ClementTsang/bottom
# License: MIT
# Binary name: btm (not bottom)
#
# build.rs (top-level) generates shell completions + a man page when:
#   BTM_GENERATE=true (runtime gate, env::var_os check)
#   COMPLETION_DIR=<path>  (compile-time option_env, where completions go)
#   MANPAGE_DIR=<path>     (compile-time option_env, where man page goes)
# Without BTM_GENERATE, build.rs no-ops — no completions, no man page.
# These exports live at the top level (outside function bodies) because
# each build phase (build/do_install) re-sources build.sh in a fresh
# subshell, and env exports inside one function don't persist to another.

export BTM_GENERATE=true
export COMPLETION_DIR="${PWD}/target/release/completion"
export MANPAGE_DIR="${PWD}/target/release/manpage"

configure() {
    set -e
    tar xf "$IGOS_SOURCES/bottom-$PKG_VERSION-vendor.tar.xz" --strip-components=1
}

build() {
    set -e
    cargo build --release --frozen --offline
}

do_install() {
    set -e
    install -Dm755 target/release/btm "$DESTDIR/usr/bin/btm"

    # Shell completions (bash/zsh/fish — skip PowerShell/Elvish/Fig/Nushell
    # which build.rs also generates but aren't shipped here).
    if [ ! -d "$COMPLETION_DIR" ]; then
        echo "ERROR: bottom completion dir not found at $COMPLETION_DIR" >&2
        exit 1
    fi
    install -Dm644 "$COMPLETION_DIR/btm.bash" \
        "$DESTDIR/usr/share/bash-completion/completions/btm"
    install -Dm644 "$COMPLETION_DIR/btm.fish" \
        "$DESTDIR/usr/share/fish/vendor_completions.d/btm.fish"
    install -Dm644 "$COMPLETION_DIR/_btm" \
        "$DESTDIR/usr/share/zsh/site-functions/_btm"

    # Man page (clap_mangen-generated by build.rs — no pandoc dep needed).
    if [ ! -f "$MANPAGE_DIR/btm.1" ]; then
        echo "ERROR: bottom man page not found at $MANPAGE_DIR/btm.1" >&2
        exit 1
    fi
    install -Dm644 "$MANPAGE_DIR/btm.1" \
        "$DESTDIR/usr/share/man/man1/btm.1"
}
