#!/bin/sh
# Install Slice B/C artifacts into the chroot before service enablement.
set -e

ART=/live-artifacts

if [ ! -d "$ART" ]; then
    echo "[fetch-artifacts] no $ART directory; skipping"
    exit 0
fi

# --- c-relay ---------------------------------------------------------------
if [ -f "$ART/c_relay_x86" ]; then
    echo "[fetch-artifacts] installing c-relay binary"
    if ! getent passwd c-relay >/dev/null 2>&1; then
        adduser --system --no-create-home --group --home /opt/c-relay c-relay
    fi
    
    # --- nostr-id-tui -----------------------------------------------------------
    if [ -f "$ART/nostr-id-tui_x86_64" ]; then
        echo "[fetch-artifacts] installing nostr-id-tui binary"
        install -m 0755 -o root -g root \
            "$ART/nostr-id-tui_x86_64" /usr/local/sbin/nostr-id-tui
    else
        echo "[fetch-artifacts] WARNING: $ART/nostr-id-tui_x86_64 not found" >&2
    fi

    mkdir -p /opt/c-relay
    install -m 0755 -o c-relay -g c-relay \
        "$ART/c_relay_x86" /opt/c-relay/c_relay_x86
    chown -R c-relay:c-relay /opt/c-relay
else
    echo "[fetch-artifacts] WARNING: $ART/c_relay_x86 not found" >&2
fi

# --- fips ------------------------------------------------------------------
FIPS_DEB=$(ls "$ART"/fips_*_amd64.deb 2>/dev/null | head -1 || true)
if [ -n "$FIPS_DEB" ] && [ -f "$FIPS_DEB" ]; then
    echo "[fetch-artifacts] installing fips package $FIPS_DEB"
    # Non-interactive: keep current /etc/fips/fips.yaml (provided by includes.chroot)
    DEBIAN_FRONTEND=noninteractive dpkg -i --force-confold "$FIPS_DEB"
else
    echo "[fetch-artifacts] WARNING: no fips_*_amd64.deb found under $ART" >&2
fi
