#!/bin/sh
# SPEC_711 PHASE F: the Chrome-model postinst. On a bare-.deb install this
# registers the OpenBloom apt repo so NO install path is a dead end for
# updates. Best-effort by design: the signing key arrives with row 6, and
# a missing key or a flaky mirror must NEVER break the package install.
set -e

KEYRING_DIR="/etc/apt/keyrings"
KEYRING="$KEYRING_DIR/openbloom.asc"
SOURCES_LIST="/etc/apt/sources.list.d/openbloom.list"
REPO_LINE="deb [signed-by=$KEYRING] https://www.openbloom.eu/updates/apt stable main"
# Row 6 maps the signing key into the deb (deb.files); every candidate
# location is checked so this script survives the packaging layout. The
# The primary candidate rides the resources root (renamed to OpenBloom
# by the SPEC_712 productName decision); the legacy spaced path stays
# as a fallback candidate.
install_key() {
    for bundled in \
        "/usr/lib/OpenBloom/resources/openbloom.asc" \
        "/usr/lib/OpenBloom Engine/resources/openbloom.asc" \
        "/usr/lib/OpenBloom/resources/packaging/openbloom.asc" \
        "/usr/share/openbloom-engine/resources/packaging/openbloom.asc" \
        "/usr/share/openbloom-engine/packaging/openbloom.asc"; do
        if [ -f "$bundled" ]; then
            mkdir -p "$KEYRING_DIR"
            chmod 0755 "$KEYRING_DIR" 2>/dev/null || true
            install -m 0644 "$bundled" "$KEYRING"
            return 0
        fi
    done
    return 1
}

register_repo() {
    if [ -f "$SOURCES_LIST" ] && grep -qF "$REPO_LINE" "$SOURCES_LIST"; then
        return 0
    fi
    mkdir -p "$(dirname "$SOURCES_LIST")"
    printf '%s\n' "$REPO_LINE" > "$SOURCES_LIST"
}

# The key is best-effort (row 6 ships it); the repo entry only helps once
# the keyring exists, apt refuses a signed-by file it cannot read.
if install_key; then
    register_repo
fi

# Refresh the package lists so the repo is usable right away; a mirror
# hiccup during an offline install is not a failure.
if command -v apt-get >/dev/null 2>&1; then
    apt-get update || true
fi

# SPEC_714 PHASE Ctierce — the openbloom:// scheme handler: the desktop
# file carries MimeType=x-scheme-handler/openbloom; the MIME database
# refresh wires xdg-open to the app. Best-effort, like the rest.
if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database /usr/share/applications || true
fi

exit 0
