#!/bin/bash
# gbuild - Glacier Package Builder
# Compiles a source directory and produces a glacier-compliant .gpkg bundle
# (compiled binary tree + .gpm.cfg manifest)

set -euo pipefail

# ---------------------------------------------------------------------------
# Colour / logging helpers — matches glacier lg_printf() in log.c
#   LG_INFO    = 0  ->  [i]  blue
#   LG_WARN    = 1  ->  [!]  yellow
#   LG_ERR     = 2  ->  [x]  red
#   LG_SUCCESS = 3  ->  [✓]  green  (falls back to [*] if not UTF-8)
# ---------------------------------------------------------------------------
_COL_RESET="\033[0m"
_COL_BLUE="\033[0;34m"
_COL_YELLOW="\033[0;33m"
_COL_RED="\033[0;31m"
_COL_GREEN="\033[0;32m"
_COL_BOLD="\033[1m"

# Check UTF-8 support once at startup
if [[ "$(locale charmap 2>/dev/null)" == "UTF-8" ]]; then
        _CHECK="\xe2\x9c\x93" # ✓
else
        _CHECK="*"
fi

log_info() { printf "${_COL_BLUE}[i]${_COL_RESET} $*\n"; }
log_warn() { printf "${_COL_YELLOW}[!]${_COL_RESET} $*\n"; }
log_err() { printf "${_COL_RED}[x]${_COL_RESET} $*\n" >&2; }
log_success() { printf "${_COL_GREEN}[${_CHECK}]${_COL_RESET} $*\n"; }
log_step() { printf "\n${_COL_BOLD}==> $*${_COL_RESET}\n"; }

die() {
        log_err "$*"
        exit 1
}

# ---------------------------------------------------------------------------
# Usage
# ---------------------------------------------------------------------------
usage() {
        local prog="$0"
        printf "%s: Build and package source code into a Glacier-compliant .gpkg\n" "$prog"
        printf "usage: %s [-hvs] [-n NAME] [-V VER] [-d DESC] [-m MAINT] [-c COPY]\n" "$prog"
        printf "       %s [-b CMD] [-i CMD] [-o DIR] [-p DIR] [-j N]\n" "$prog"
        printf "       %s [-D name:ver] [-C name:ver] <SOURCE_DIR>\n\n" "$prog"
        printf "%-35s %s\n" "{-h --help}" "Show this message"
        printf "%-35s %s\n\n" "{-v --version}" "Show the current version"
        printf "%-35s %s\n" "{-n --name} NAME" "Package name (default: basename of SOURCE_DIR)"
        printf "%-35s %s\n" "{-V --ver} VERSION" "Semantic version (default: 0.1.0)"
        printf "%-35s %s\n" "{-d --desc} DESC" "Short description (prompted if omitted)"
        printf "%-35s %s\n" "{-m --maint} MAINT" "Maintainer e-mail (prompted if omitted)"
        printf "%-35s %s\n" "{-c --copy} COPYRIGHT" "Copyright string (default: MIT)"
        printf "%-35s %s\n" "{-g --repo} REPO" "Package repo (default: local — e.g. base, core, community, nonfree)"
        printf "%-35s %s\n" "{-D --dep} name:ver" "Add a dependency, e.g. libfoo:1.0.0"
        printf "%-35s %s\n" "{-C --conf} name:ver" "Add a conflict, e.g. old-foo:0.9.0"
        printf "%-35s %s\n" "{-b --build} CMD" "Build command (default: autodetected)"
        printf "%-35s %s\n" "{-i --install} CMD" "Install command populating \$DESTDIR"
        printf "%-35s %s\n" "{-o --output} DIR" "Output directory for finished .gpkg (default: .)"
        printf "%-35s %s\n" "{-p --stage} DIR" "Staging DESTDIR to inspect after build"
        printf "%-35s %s\n" "{-j --jobs} N" "Parallel build jobs (default: nproc)"
        printf "%-35s %s\n" "{-F --flags} FLAGS" "Extra compiler flags, e.g. \"-O2 -fstack-protector-strong\""
        printf "%-35s %s\n" "{-t --toolchain} DIR" "Path to toolchain bin directory, e.g. ~/x86_64-linux-musl-cross/bin"
        printf "%-35s %s\n" "{-x --cross-prefix} P" "Toolchain prefix, e.g. x86_64-linux-musl (default: autodetected)"
        printf "%-35s %s\n" "{-u --url} URL" "Git repository URL to clone"
        printf "%-35s %s\n" "{-r --ref} REF" "Git tag, branch, or commit to check out (default: default branch)"
        printf "%-35s %s\n" "{-k --key} KEY.sec" "Sign the sidecar with this secret key (writes .sha256.sig)"
        printf "%-35s %s\n\n" "{--verbose}" "Log events more verbosely"
        printf "This program is free software.\n"
        printf "See the GNU GPL version 3 for details.\n"
}

# ---------------------------------------------------------------------------
# Defaults
# ---------------------------------------------------------------------------
PKG_NAME=""
PKG_VER="0.1.0"
PKG_DESC=""
PKG_MAINT=""
PKG_COPYRIGHT="MIT"
PKG_REPO="local"
BUILD_CMD=""
INSTALL_CMD=""
OUTPUT_DIR="."
STAGE_DIR=""
JOBS="$(nproc 2>/dev/null || echo 4)"
SKIP_BUILD=0
VERBOSE=0
DEPS=()
CONFS=()
EXTRA_CFLAGS=""
TOOLCHAIN_DIR=""
TOOLCHAIN_PREFIX=""
REPO_URL=""
REPO_REF=""
SIGN_KEY=""

# ---------------------------------------------------------------------------
# Parse options — convert longopts to shortopts before getopts runs
# ---------------------------------------------------------------------------

# Map of --longopt -> shortopt
declare -A _LONGOPTS=(
        [--repo]="-g"
    [--help]="-h"
        [--version]="-v"
        [--name]="-n"
        [--ver]="-V"
        [--desc]="-d"
        [--maint]="-m"
        [--copy]="-c"
        [--dep]="-D"
        [--conf]="-C"
        [--build]="-b"
        [--install]="-i"
        [--output]="-o"
        [--stage]="-p"
        [--jobs]="-j"
        [--flags]="-F"
        [--toolchain]="-t"
        [--cross-prefix]="-x"
        [--skip]="-s"
        [--verbose]="-e"
        [--url]="-u"
        [--ref]="-r"
        [--key]="-k"
)

# Rewrite argv replacing any --long-opt[=val] with -s [val]
_args=()
for _arg in "$@"; do
        if [[ "$_arg" == --*=* ]]; then
                # --key=value  ->  -s value
                _key="${_arg%%=*}"
                _val="${_arg#*=}"
                _short="${_LONGOPTS[$_key]:-}"
                [[ -z "$_short" ]] && die "Unknown option: $_key"
                _args+=("$_short" "$_val")
        elif [[ "$_arg" == --* ]]; then
                # --key  ->  -s
                _short="${_LONGOPTS[$_arg]:-}"
                [[ -z "$_short" ]] && die "Unknown option: $_arg"
                _args+=("$_short")
        else
                _args+=("$_arg")
        fi
done
set -- "${_args[@]+"${_args[@]}"}"

# -v is --version (as documented); verbose is long-only (--verbose), mapped
# to the otherwise unused -e above.
while getopts ":n:V:d:m:c:g:D:C:b:i:o:p:j:F:t:x:u:r:k:svhe" opt; do
        case $opt in
        n) PKG_NAME="$OPTARG" ;;
        V) PKG_VER="$OPTARG" ;;
        d) PKG_DESC="$OPTARG" ;;
        m) PKG_MAINT="$OPTARG" ;;
        c) PKG_COPYRIGHT="$OPTARG" ;;
        g) PKG_REPO="$OPTARG" ;;
        D) DEPS+=("$OPTARG") ;;
        C) CONFS+=("$OPTARG") ;;
        b) BUILD_CMD="$OPTARG" ;;
        i) INSTALL_CMD="$OPTARG" ;;
        o) OUTPUT_DIR="$OPTARG" ;;
        p) STAGE_DIR="$OPTARG" ;;
        j) JOBS="$OPTARG" ;;
        F) EXTRA_CFLAGS="$OPTARG" ;;
        t) TOOLCHAIN_DIR="$OPTARG" ;;
        x) TOOLCHAIN_PREFIX="$OPTARG" ;;
        u) REPO_URL="$OPTARG" ;;
        r) REPO_REF="$OPTARG" ;;
        k) SIGN_KEY="$OPTARG" ;;
        s) SKIP_BUILD=1 ;;
        v)
                echo "v4.0.0"
                exit 0
                ;;
        e) VERBOSE=1 ;;
        h)
                usage
                exit 0
                ;;
        :) die "Option -$OPTARG requires an argument." ;;
        \?) die "Unknown option: -$OPTARG" ;;
        esac
done
shift $((OPTIND - 1))

# ---------------------------------------------------------------------------
# Locate gsha256sum (and gsign, for -k)
#
# Resolution order (shown for gsha256sum; gsign's variable is $GSIGN_BIN):
#   1. $GSHA256SUM_BIN, if the caller set it explicitly
#   2. relative to this script's own location — ../bin/gsha256sum, which
#      is where `make install` puts it relative to $PREFIX/gbuild if
#      gbuild itself is being run from $PREFIX. This is what makes a
#      project-local, non-PATH PREFIX (e.g. PREFIX=~/Projects/glacier-ng)
#      work without the caller having to export PATH themselves.
#   3. bare `gsha256sum` on PATH, same as how git/tar/make are already
#      invoked elsewhere in this script — the fallback for a real
#      system-wide install where $PREFIX/bin IS on PATH.
#
# Resolved here (after option parsing, so -h/--help never needs this;
# before any clone/build work, so a missing gsha256sum fails fast rather
# than after minutes of building something that can't be hashed at the
# end anyway) once, so every later call site just uses $GSHA256SUM.
# ---------------------------------------------------------------------------
resolve_tool() {
        local tool="$1" var="$2"
        local explicit="${!var:-}"
        if [[ -n "$explicit" ]]; then
                if [[ ! -x "$explicit" ]]; then
                        die "\$$var is set to '$explicit' but that isn't executable."
                fi
                echo "$explicit"
                return
        fi

        local script_dir
        script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        # gbuild runs from the source checkout, NOT from inside $PREFIX —
        # $PREFIX is arbitrary and unrelated to where this script lives.
        # What IS guaranteed by the Makefile is that `make` (before any
        # `make install`) drops the freshly-built binary at build/bin/
        # right next to this script, in the same source tree.
        local candidate="$script_dir/build/bin/$tool"
        if [[ -x "$candidate" ]]; then
                echo "$candidate"
                return
        fi

        if command -v "$tool" >/dev/null 2>&1; then
                echo "$tool"
                return
        fi

        die "Could not find $tool (checked \$$var, $candidate, and PATH). Run 'make install' first, or set $var explicitly."
}

GSHA256SUM="$(resolve_tool gsha256sum GSHA256SUM_BIN)" || exit 1
GSIGN=""
if [[ -n "$SIGN_KEY" ]]; then
        GSIGN="$(resolve_tool gsign GSIGN_BIN)" || exit 1
        # Fail before building, not after: sign a throwaway file now.
        _probe="$(mktemp)" || die "Cannot create a temporary file."
        _out="$("$GSIGN" -S -s "$SIGN_KEY" -m "$_probe" -x "$_probe.sig" 2>&1)" ||
                { rm -f "$_probe" "$_probe.sig"; printf '%s\n' "$_out" >&2; exit 1; }
        rm -f "$_probe" "$_probe.sig"
fi

[[ $# -lt 1 ]] && [[ -z "$REPO_URL" ]] && {
        log_err "usage: $0 [-hvs] [-nVdmcDCbiojpur] <SOURCE_DIR>"
        exit 1
}

if [[ -z "$REPO_URL" ]]; then
        SOURCE_DIR="${1%/}"
        [[ -d "$SOURCE_DIR" ]] || die "Source directory '$SOURCE_DIR' does not exist."
        SOURCE_DIR="$(realpath "$SOURCE_DIR")"
fi

# ---------------------------------------------------------------------------
# Fill in defaults that depend on SOURCE_DIR
# ---------------------------------------------------------------------------
[[ -z "$PKG_NAME" ]] && [[ -n "$SOURCE_DIR" ]] && PKG_NAME="$(basename "$SOURCE_DIR")"
[[ -z "$PKG_NAME" ]] && [[ -n "$REPO_URL" ]] && PKG_NAME="$(basename "$REPO_URL" .git)"

# ---------------------------------------------------------------------------
# Validate semver format
# ---------------------------------------------------------------------------
validate_semver() {
        local v="$1"
        # strip optional pre-release tag  (e.g. 1.2.3-alpha)
        local core="${v%%-*}"
        [[ "$core" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ||
                die "Version '$v' is not valid semver (expected MAJOR.MINOR.PATCH[-tag])."
}
validate_semver "$PKG_VER"

# ---------------------------------------------------------------------------
# Interactive prompts for missing required fields
# ---------------------------------------------------------------------------
prompt_if_empty() {
        local varname="$1"
        local prompt_text="$2"
        local default="$3"
        local current
        current="${!varname}"
        if [[ -z "$current" ]]; then
                if [[ -t 0 ]]; then
                        read -rp "$(printf "${_COL_BLUE}[i]${_COL_RESET} ${prompt_text} [${default}]: ")" val
                        val="${val:-$default}"
                else
                        val="$default"
                fi
                printf -v "$varname" '%s' "$val"
        fi
}

prompt_if_empty PKG_DESC "Short description" "A Glacier package"
prompt_if_empty PKG_MAINT "Maintainer e-mail" "unknown@localhost"

# ---------------------------------------------------------------------------
# Dependency / conflict format validation:  name:MAJOR.MINOR.PATCH
# ---------------------------------------------------------------------------
parse_dep_or_conf() {
        local raw="$1"
        local label="$2" # "dependency" or "conflict"
        local name ver
        name="${raw%%:*}"
        ver="${raw#*:}"
        [[ "$name" =~ ^[a-zA-Z0-9_-]+$ ]] ||
                die "Invalid $label name in '$raw'. Use alphanumeric/hyphen/underscore."
        validate_semver "$ver" 2>/dev/null ||
                die "Invalid $label version in '$raw'. Expected name:MAJOR.MINOR.PATCH."
        echo "$name $ver"
}

# ---------------------------------------------------------------------------
# Toolchain setup
# If -t is given, locate the compiler in that directory.
# If -x is also given, use it as the prefix (e.g. x86_64-linux-musl).
# If -x is omitted, autodetect by scanning the toolchain bin dir for *-gcc.
# If neither is given, fall back to the system CC/CXX.
# ---------------------------------------------------------------------------
setup_toolchain() {
        if [[ -z "$TOOLCHAIN_DIR" ]]; then
                # No toolchain specified — use system compiler
                CC="${CC:-cc}"
                CXX="${CXX:-c++}"
                AR="${AR:-ar}"
                export CC CXX AR
                log_info "Toolchain: system (${CC})"
                return
        fi

        [[ -d "$TOOLCHAIN_DIR" ]] ||
                die "Toolchain directory '$TOOLCHAIN_DIR' does not exist."

        TOOLCHAIN_DIR="$(realpath "$TOOLCHAIN_DIR")"

        # Autodetect prefix if not supplied
        if [[ -z "$TOOLCHAIN_PREFIX" ]]; then
                local detected
                detected="$(find "$TOOLCHAIN_DIR" -maxdepth 1 -name '*-gcc' |
                        head -1 | xargs basename 2>/dev/null)"
                [[ -n "$detected" ]] ||
                        die "Could not autodetect toolchain prefix in '$TOOLCHAIN_DIR'. Use -x to specify it."
                TOOLCHAIN_PREFIX="${detected%-gcc}"
                log_info "Autodetected toolchain prefix: $TOOLCHAIN_PREFIX"
        fi

        local tc_cc="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-gcc"
        local tc_cxx="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-g++"
        local tc_ar="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-ar"

        [[ -x "$tc_cc" ]] || die "Toolchain compiler not found: $tc_cc"
        [[ -x "$tc_ar" ]] || die "Toolchain ar not found: $tc_ar"

        export CC="$tc_cc"
        export CXX="$tc_cxx"
        export AR="$tc_ar"
        export CROSS_COMPILE="${TOOLCHAIN_PREFIX}-"

        # Prepend toolchain bin dir to PATH so make/cmake/meson find the
        # prefixed binaries when they search by name rather than full path
        export PATH="$TOOLCHAIN_DIR:$PATH"

        log_info "Toolchain: $TOOLCHAIN_PREFIX"
        log_info "  CC  = $CC"
        log_info "  CXX = $CXX"
        log_info "  AR  = $AR"
}
setup_toolchain

# ---------------------------------------------------------------------------
# Clone source from git if -u was supplied
# ---------------------------------------------------------------------------
clone_source() {
        local clone_dir
        clone_dir="$(mktemp -d /tmp/gbuild_clone.XXXXXXXX)"

        if [[ -n "$REPO_REF" ]]; then
                # Try shallow clone with --branch first (works for tags and branches)
                if ! git clone --branch "$REPO_REF" --depth 1 "$REPO_URL" "$clone_dir" 2>/dev/null; then
                        # Fall back to full clone + checkout for commit hashes
                        # stderr: stdout is the clone dir, captured by the caller
                        log_warn "Shallow clone failed, falling back to full clone for commit checkout..." >&2
                        rm -rf "$clone_dir"
                        clone_dir="$(mktemp -d /tmp/gbuild_clone.XXXXXXXX)"
                        git clone "$REPO_URL" "$clone_dir" >&2 \
                                || die "Failed to clone $REPO_URL"
                        git -C "$clone_dir" checkout "$REPO_REF" >&2 \
                                || die "Failed to check out ref $REPO_REF"
                fi
        else
                git clone --depth 1 "$REPO_URL" "$clone_dir" \
                        || die "Failed to clone $REPO_URL"
        fi

        echo "$clone_dir"
}

# ---------------------------------------------------------------------------
# Build system autodetection
# ---------------------------------------------------------------------------
detect_build_system() {
        local src="$1"

        if [[ -f "$src/CMakeLists.txt" ]]; then
                echo "cmake"
        elif [[ -f "$src/meson.build" ]]; then
                echo "meson"
        elif [[ -f "$src/Cargo.toml" ]]; then
                echo "cargo"
        elif [[ -f "$src/go.mod" ]]; then
                echo "go"
        # configure BEFORE a bare Makefile: musl and plenty of hand-rolled
        # projects ship both, and running make without configure builds
        # with the wrong defaults (CLAUDE.md bug 8, regressed once already).
        elif [[ -f "$src/configure" ]] ||
                [[ -f "$src/configure.ac" ]]; then
                echo "autotools"
        elif [[ -f "$src/Makefile" ]] ||
                [[ -f "$src/GNUmakefile" ]]; then
                echo "make"
        else
                echo "unknown"
        fi
}

# ---------------------------------------------------------------------------
# Run a command, honouring VERBOSE
# ---------------------------------------------------------------------------
run_cmd() {
        if [[ $VERBOSE -eq 1 ]]; then
                "$@"
        else
                "$@" >/tmp/gbuild_cmd.log 2>&1 ||
                        {
                                log_err "Command failed: $*"
                                cat /tmp/gbuild_cmd.log >&2
                                exit 1
                        }
        fi
}

# ---------------------------------------------------------------------------
# Build step
# ---------------------------------------------------------------------------
do_build() {
        local src="$1"
        local destdir="$2"
        local bsys

        bsys="$(detect_build_system "$src")"
        log_info "Detected build system: $(printf "${_COL_BOLD}")${bsys}$(printf "${_COL_RESET}")"

        # Export extra compiler flags so all build systems inherit them
        if [[ -n "$EXTRA_CFLAGS" ]]; then
                log_info "Extra compiler flags: $EXTRA_CFLAGS"
                export CFLAGS="${CFLAGS:-} $EXTRA_CFLAGS"
                export CXXFLAGS="${CXXFLAGS:-} $EXTRA_CFLAGS"
        fi

        # --- override if user supplied either build or install command ---
        if [[ -n "$BUILD_CMD" ]] || [[ -n "$INSTALL_CMD" ]]; then
                local effective_build="${BUILD_CMD:-make}"
                local effective_install="${INSTALL_CMD:-make install}"

                log_step "Building with custom command: $effective_build"
                pushd "$src" >/dev/null
                run_cmd bash -c "$effective_build"
                popd >/dev/null

                log_step "Installing into staging area"
                pushd "$src" >/dev/null
                run_cmd bash -c "export DESTDIR='$destdir'; $effective_install"
                popd >/dev/null
                return
        fi

        # --- autodetected paths ---
        case "$bsys" in

        make)
                log_step "Building with make"
                pushd "$src" >/dev/null
                run_cmd make -j"$JOBS"
                popd >/dev/null

                log_step "Installing into staging area (make install)"
                pushd "$src" >/dev/null
                run_cmd make install DESTDIR="$destdir"
                popd >/dev/null
                ;;

        autotools)
                log_step "Running ./configure"
                pushd "$src" >/dev/null
                [[ -f configure ]] || run_cmd autoreconf -fi
                run_cmd ./configure --prefix=/usr
                popd >/dev/null

                log_step "Building with make"
                pushd "$src" >/dev/null
                run_cmd make -j"$JOBS"
                popd >/dev/null

                log_step "Installing into staging area"
                pushd "$src" >/dev/null
                run_cmd make install DESTDIR="$destdir"
                popd >/dev/null
                ;;

        cmake)
                local build_dir="$src/_gbuild_cmake"
                mkdir -p "$build_dir"
                log_step "Configuring with CMake"
                run_cmd cmake -S "$src" -B "$build_dir" \
                        -DCMAKE_BUILD_TYPE=Release \
                        -DCMAKE_INSTALL_PREFIX=/usr \
                        -DCMAKE_C_COMPILER="$CC" \
                        -DCMAKE_CXX_COMPILER="${CXX:-c++}" \
                        ${EXTRA_CFLAGS:+-DCMAKE_C_FLAGS="$EXTRA_CFLAGS"} \
                        ${EXTRA_CFLAGS:+-DCMAKE_CXX_FLAGS="$EXTRA_CFLAGS"}

                log_step "Building with CMake"
                run_cmd cmake --build "$build_dir" --parallel "$JOBS"

                log_step "Installing into staging area"
                run_cmd cmake --install "$build_dir" --prefix "$destdir/usr"
                ;;

        meson)
                local build_dir="$src/_gbuild_meson"
                log_step "Configuring with Meson"
                run_cmd env CC="$CC" CXX="${CXX:-c++}" \
                        meson setup "$build_dir" "$src" \
                        --prefix=/usr \
                        --buildtype=release \
                        ${EXTRA_CFLAGS:+-Dc_args="$EXTRA_CFLAGS"} \
                        ${EXTRA_CFLAGS:+-Dcpp_args="$EXTRA_CFLAGS"}

                log_step "Building with Ninja"
                run_cmd ninja -C "$build_dir" -j"$JOBS"

                log_step "Installing into staging area"
                run_cmd env DESTDIR="$destdir" ninja -C "$build_dir" install
                ;;

        cargo)
                log_step "Building with Cargo (release)"
                pushd "$src" >/dev/null
                run_cmd cargo build --release
                popd >/dev/null

                log_step "Staging Cargo binary"
                local bin_name="$PKG_NAME"
                local cargo_bin="$src/target/release/$bin_name"
                if [[ ! -f "$cargo_bin" ]]; then
                        # try to find any release binary
                        cargo_bin="$(find "$src/target/release" -maxdepth 1 \
                                -type f -executable ! -name '*.d' | head -1)"
                fi
                [[ -f "$cargo_bin" ]] || die "Could not locate Cargo release binary."
                mkdir -p "$destdir/usr/bin"
                cp "$cargo_bin" "$destdir/usr/bin/$PKG_NAME"
                ;;

        go)
                log_step "Building with Go"
                pushd "$src" >/dev/null
                run_cmd go build -o "$PKG_NAME" ./...
                popd >/dev/null

                log_step "Staging Go binary"
                mkdir -p "$destdir/usr/bin"
                cp "$src/$PKG_NAME" "$destdir/usr/bin/$PKG_NAME"
                ;;

        unknown)
                die "Could not detect a build system in '$src'. " \
                        "Use -b BUILD_CMD and -i INSTALL_CMD to specify commands manually."
                ;;
        esac
}

# ---------------------------------------------------------------------------
# Generate the .gpm.cfg manifest  (libconfig syntax used by gl_gpm2gpkg)
# ---------------------------------------------------------------------------
write_manifest() {
        local manifest_path="$1"
        shift

        # split semver + optional tag
        local ver_core="${PKG_VER%%-*}"
        local ver_tag=""
        [[ "$PKG_VER" == *-* ]] && ver_tag="${PKG_VER#*-}"

        local maj min pat
        IFS='.' read -r maj min pat <<<"$ver_core"

        {
                echo "// Glacier Package Manifest"
                echo "// Generated by gbuild on $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
                echo ""
                echo "PKG_NAME      = \"${PKG_NAME}\";"
                if [[ -n "$ver_tag" ]]; then
                        echo "PKG_VER       = \"${maj}.${min}.${pat}-${ver_tag}\";"
                else
                        echo "PKG_VER       = \"${maj}.${min}.${pat}\";"
                fi
                echo "PKG_DESC      = \"${PKG_DESC}\";"
                echo "PKG_MAINT     = \"${PKG_MAINT}\";"
                echo "PKG_COPYRIGHT = \"${PKG_COPYRIGHT}\";"
                echo "PKG_REPO     = \"${PKG_REPO}\";"
                echo ""

                # Dependencies
                if [[ ${#DEPS[@]} -gt 0 ]]; then
                        echo "PKG_DEPS = ("
                        for raw in "${DEPS[@]}"; do
                                read -r dname dver <<<"$(parse_dep_or_conf "$raw" "dependency")"
                                local dmaj dmin dpat
                                IFS='.' read -r dmaj dmin dpat <<<"$dver"
                                echo "    {"
                                echo "        PKG_NAME = \"${dname}\";"
                                echo "        PKG_VER  = \"${dmaj}.${dmin}.${dpat}\";"
                                echo "    },"
                        done
                        echo ");"
                else
                        echo "PKG_DEPS = ();"
                fi
                echo ""

                # Conflicts
                if [[ ${#CONFS[@]} -gt 0 ]]; then
                        echo "PKG_CONFS = ("
                        for raw in "${CONFS[@]}"; do
                                read -r cname cver <<<"$(parse_dep_or_conf "$raw" "conflict")"
                                local cmaj cmin cpat
                                IFS='.' read -r cmaj cmin cpat <<<"$cver"
                                echo "    {"
                                echo "        PKG_NAME = \"${cname}\";"
                                echo "        PKG_VER  = \"${cmaj}.${cmin}.${cpat}\";"
                                echo "    },"
                        done
                        echo ");"
                else
                        echo "PKG_CONFS = ();"
                fi

        } >"$manifest_path"
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
log_step "gbuild — Glacier Package Builder"
[[ -n "$REPO_URL" ]] && log_info "URL:       $REPO_URL"
[[ -n "$REPO_REF" ]] && log_info "Ref:       $REPO_REF"
log_info "Package:   $PKG_NAME  $PKG_VER"
log_info "Maintainer: $PKG_MAINT"
[[ -n "$EXTRA_CFLAGS" ]] && log_info "Flags:     $EXTRA_CFLAGS"
[[ -n "$TOOLCHAIN_PREFIX" ]] && log_info "Target:    $TOOLCHAIN_PREFIX"

# Clone source if -u was supplied
if [[ -n "$REPO_URL" ]]; then
        log_step "Cloning source repository"
        SOURCE_DIR="$(clone_source)"
        log_success "Cloned to $SOURCE_DIR"
        # Clean up clone dir on exit alongside WORK_DIR
        trap 'rm -rf "$WORK_DIR" "$SOURCE_DIR"' EXIT
fi

[[ -z "$PKG_NAME" ]] && PKG_NAME="$(basename "$SOURCE_DIR")"
PKG_NAME="${PKG_NAME//[^a-zA-Z0-9-]/}"
PKG_NAME="${PKG_NAME,,}"
[[ -z "$PKG_NAME" ]] && die "Could not derive a valid package name."

log_info "Source:    $SOURCE_DIR"

# Create working directories
WORK_DIR="$(mktemp -d /tmp/gbuild.XXXXXXXX)"
PKG_DIR="$WORK_DIR/pkg"
mkdir -p "$PKG_DIR"

# DESTDIR: use user-supplied staging dir if given, otherwise temp
if [[ -n "$STAGE_DIR" ]]; then
        DESTDIR="$(realpath "$STAGE_DIR")"
        mkdir -p "$DESTDIR"
        log_info "Staging dir: $DESTDIR"
        # Don't clean up STAGE_DIR on exit — user wants to inspect it
        trap 'rm -rf "$WORK_DIR"' EXIT
else
        DESTDIR="$WORK_DIR/destdir"
        mkdir -p "$DESTDIR"
        trap 'rm -rf "$WORK_DIR"' EXIT
fi

# --- Build ---
if [[ $SKIP_BUILD -eq 0 ]]; then
        do_build "$SOURCE_DIR" "$DESTDIR"
        log_success "Build complete."
else
        log_warn "Skipping build step (-s flag set)."
fi

# --- Assemble package directory ---
# Layout inside the .gpkg dir:
#   <pkgname>-<ver>/
#       manifest.gpm.cfg        <- parsed by gl_gpm2gpkg
#       files/                  <- the DESTDIR tree (what gets installed)

PKG_FULL_NAME="${PKG_NAME}-${PKG_VER}"
PKG_STAGE="$PKG_DIR/$PKG_FULL_NAME"
mkdir -p "$PKG_STAGE/files"

log_step "Assembling package layout"

# Copy staged files
if [[ $SKIP_BUILD -eq 0 ]]; then
        if [[ -n "$(ls -A "$DESTDIR" 2>/dev/null)" ]]; then
                cp -a "$DESTDIR/." "$PKG_STAGE/files/"
                log_info "Staged file tree copied."
        else
                log_warn "DESTDIR is empty — the package will contain no files."
                log_warn "Check your build/install commands."
        fi
fi

# Write manifest
MANIFEST_PATH="$PKG_STAGE/manifest.gpm.cfg"
write_manifest "$MANIFEST_PATH"
log_success "Manifest written: manifest.gpm.cfg"

if [[ $VERBOSE -eq 1 ]]; then
        log_info "--- manifest.gpm.cfg ---"
        cat "$MANIFEST_PATH"
        echo ""
fi

# --- Archive and compress into OUTPUT_DIR ---
OUTPUT_DIR="$(realpath "$OUTPUT_DIR")"
mkdir -p "$OUTPUT_DIR"
FINAL_PKG="$OUTPUT_DIR/$PKG_FULL_NAME.gpkg"

log_step "Compressing package"

# Remove old output if present
rm -f "$FINAL_PKG"

# Hardlinks become plain files: glacier refuses a package with a
# hardlink entry (binutils installs ld as a hardlink to ld.bfd).
find "$PKG_DIR/$PKG_FULL_NAME" -type f -links +1 | while IFS= read -r f; do
        cp -p "$f" "$f.unlink" && mv -f "$f.unlink" "$f" ||
                die "Cannot copy hardlink $f."
done

# tar the staged package directory, compress with gzip, write to .gpkg
# -C into the parent so the archive root is just <pkgname>-<ver>/
tar -czf "$FINAL_PKG" -C "$PKG_DIR" "$PKG_FULL_NAME" ||
        die "Failed to create package archive."

log_step "Hashing package"
SIDECAR_PATH="$FINAL_PKG.sha256"
"$GSHA256SUM" "$FINAL_PKG" > "$SIDECAR_PATH" ||
        die "Failed to hash package archive."
log_success "Sidecar: ${_COL_BOLD}${SIDECAR_PATH}${_COL_RESET}"
log_info "$(cat "$SIDECAR_PATH")"

rm -f "$SIDECAR_PATH.sig"
if [[ -n "$SIGN_KEY" ]]; then
        log_step "Signing sidecar"
        _out="$("$GSIGN" -S -s "$SIGN_KEY" -m "$SIDECAR_PATH" 2>&1)" ||
                { printf '%s\n' "$_out" >&2; exit 1; }
        log_success "Signature: ${_COL_BOLD}${SIDECAR_PATH}.sig${_COL_RESET}"
fi

log_step "Package ready"
log_success "Output: ${_COL_BOLD}${FINAL_PKG}${_COL_RESET}"
log_info "Size: $(du -sh "$FINAL_PKG" | cut -f1)"
echo ""
log_info "Contents:"
tar -tzf "$FINAL_PKG" | sort | while read -r line; do
        printf "  %s\n" "$line"
done
