#!/bin/bash
# InterGenOS Steam client installer.
#
# Downloads Valve's steam-launcher from the SIGNED apt repo
# (repo.steampowered.com, component `steam`, package steam-launcher
# amd64), verifies the signed-Release integrity chain with the SCOPED
# weak-digest posture (operator decision 2), installs the payload under
# /usr/lib/steam, and manifest-tracks the footprint. /usr/bin/steam (the
# fail-closed wrapper) and the closure manifest ship with the package.

set -e

source /usr/share/igos/helpers/helper-lib.sh

ACCEPTANCE_DIR="/var/lib/intergen/legal"
ACCEPTANCE_FILE="$ACCEPTANCE_DIR/steam-1.0-accepted.json"

STEAM_APT_BASE="https://repo.steampowered.com/steam"
STEAM_DIST="stable"
STEAM_COMPONENT="steam"        # NOT main
STEAM_PKG_NAME="steam-launcher"
STEAM_KEYRING="/usr/share/igos/helpers/keyrings/steam-keyring.gpg"
# Valve's pinned primary key fingerprint (the historically-SHA1 2012 key
# steam-for-linux#12050 is about). The scoped weak-digest retry accepts a
# weak SIGNATURE digest ONLY when the InRelease resolves Good to THIS key.
STEAM_KEY_FPR="BA1816EF8E75005FCF5E27A1F24AEA9FB05498B7"

TMPDIR=$(mktemp -d)
IGOS_HELPER_USER_CLEANUP="rm -rf $TMPDIR"

echo ""
echo "  InterGenOS Steam Installer"
echo "  =========================="
echo ""
echo "  Steam is proprietary software governed by the Steam Subscriber"
echo "  Agreement: https://store.steampowered.com/subscriber_agreement/"
echo ""

if [ "$(id -u)" -ne 0 ]; then
    echo "  ERROR: Run via 'sudo pkm install steam' instead."
    echo "  Installing this way does not record the files with pkm;"
    echo "  pkm files/verify/remove will not see the installed files."
    exit 1
fi

if [ -f "$ACCEPTANCE_FILE" ]; then
    echo "  Acceptance already recorded at $ACCEPTANCE_FILE"
else
    echo ""
    echo "  Do you accept the Steam Subscriber Agreement above and"
    echo "  authorize installing Steam on this machine for your own use?"
    echo "  Type 'I ACCEPT' (exact match, capitals) to proceed:"
    echo ""
    read -r REPLY
    if [ "$REPLY" != "I ACCEPT" ]; then
        echo "  Acceptance not given. Exiting."
        exit 10
    fi
    mkdir -p "$ACCEPTANCE_DIR"
    cat > "$ACCEPTANCE_FILE" <<JSON
{
  "helper": "steam",
  "version": "1.0",
  "payload_license": "LicenseRef-Valve-SSA",
  "accepted_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "user": "$(logname 2>/dev/null || echo unknown)"
}
JSON
    chmod 644 "$ACCEPTANCE_FILE"
    echo "  Acceptance recorded at $ACCEPTANCE_FILE"
fi

igos_helper_init "steam"
igos_helper_record_post_install_action \
    "User accepted the Steam Subscriber Agreement (acceptance artifact at $ACCEPTANCE_FILE)"

echo "  Finding steam-launcher in Valve's signed apt metadata (component ${STEAM_COMPONENT})..."
LATEST=$(igos_helper_find_latest_deb_in_packages "$STEAM_PKG_NAME" "$STEAM_APT_BASE" "$STEAM_DIST" "$STEAM_COMPONENT")
if [ -z "$LATEST" ]; then
    echo "  ERROR: Could not locate steam-launcher in the official apt"
    echo "         Packages metadata at ${STEAM_APT_BASE}/dists/${STEAM_DIST}/${STEAM_COMPONENT}/"
    exit 1
fi
DEB_NAME=$(echo "$LATEST" | cut -d'|' -f1)
STEAM_VERSION=$(echo "$LATEST" | cut -d'|' -f2)
POOL_PATH=$(echo "$LATEST" | cut -d'|' -f3)
igos_helper_set_version "${STEAM_VERSION:-unknown}"

echo "  Downloading ${DEB_NAME}..."
wget -q --show-progress -O "$TMPDIR/steam.deb" "${STEAM_APT_BASE}/${POOL_PATH}"

# The SCOPED weak-digest posture (operator decision 2): STRICT-first;
# only Valve's specific SHA1 weak-digest rejection triggers a permissive
# retry, pinned to Valve's fingerprint, with the exception logged loudly.
# Honest bound (review residual, accepted 2026-07-02): on the STRICT path
# the sha256 chain binds every byte; on an ACTIVE weak-path retry, a
# SHA1-collision-forged InRelease could carry attacker-chosen SHA256
# Packages hashes, so end-to-end integrity reduces to SHA1-collision
# resistance on the InRelease — the fingerprint pin and the loud log line
# are the mitigations there, not the sha256 chain. The 6th arg is the
# component; the 7th arg (the pinned fingerprint) enables the scoped path.
echo "  Verifying Valve's signed-Release integrity chain..."
if ! igos_helper_verify_deb_via_signed_release \
    "$DEB_NAME" \
    "$TMPDIR/steam.deb" \
    "$STEAM_APT_BASE" \
    "$STEAM_KEYRING" \
    "$STEAM_DIST" \
    "$STEAM_COMPONENT" \
    "$STEAM_KEY_FPR"; then
    echo ""
    echo "  ERROR: Signed-Release verification FAILED for ${DEB_NAME}."
    echo "  Refusing to install. Do NOT extract the .deb manually."
    exit 1
fi

echo "  Extracting..."
cd "$TMPDIR"
ar x steam.deb
tar xf data.tar.xz

# Pre-flight payload-completeness gate: every path the .deb ships must
# fall under a root this helper HANDLES (installs + records) or
# DELIBERATELY excludes. A new Valve path fails loudly HERE — before
# anything is copied — instead of silently landing on disk untracked.
#   handled:  usr/lib/steam/, usr/share/, usr/bin/steamdeps, lib/udev/
#   excluded: usr/bin/steam (the fail-closed wrapper owns that path),
#             etc/apt/ (pkm owns updates, not Valve's apt sources)
UNEXPECTED=$(tar tf data.tar.xz | grep -v '/$' | sed 's|^\./||' \
    | grep -vE '^(usr/lib/steam/|usr/share/|usr/bin/steam$|usr/bin/steamdeps$|lib/udev/|etc/apt/)' || true)
if [ -n "$UNEXPECTED" ]; then
    echo "  ERROR: steam-launcher ships paths this helper does not handle:"
    echo "$UNEXPECTED" | sed 's/^/    /'
    echo "  Refusing to install. Nothing was copied onto this machine."
    exit 1
fi
echo "  Installing the Steam bootstrap under /usr/lib/steam..."
cp -a usr/lib/steam /usr/lib/

echo "  Recording the installed files with pkm..."
while IFS= read -r -d '' f; do
    igos_helper_record_file "$f"
done < <(find /usr/lib/steam \( -type f -o -type l \) -print0 2>/dev/null)

# usr/share + lib/udev payload: install + record EVERY file in one
# pass — completeness by construction. (A curated pattern list drifts
# the moment Valve adds a file; the ge-proton manifest-completeness
# standard applies: pkm remove must reach everything this install put
# on disk.)
while IFS= read -r -d '' f; do
    cp --parents -a "$f" /
    igos_helper_record_file "/$f"
done < <(find usr/share lib/udev \( -type f -o -type l \) -print0 2>/dev/null)

if [ -f usr/bin/steamdeps ]; then
    cp -a usr/bin/steamdeps /usr/bin/steamdeps
    igos_helper_record_file /usr/bin/steamdeps
fi

igos_helper_record_dep intergenos-helper-lib
igos_helper_record_dep lib32-glibc

gtk-update-icon-cache /usr/share/icons/hicolor 2>/dev/null || true
igos_helper_record_post_install_action \
    "gtk-update-icon-cache /usr/share/icons/hicolor"

igos_helper_commit

echo ""
echo "  Steam installed. Launch it with: steam"
echo ""
