#!/bin/bash
# InterGenOS Zoom Workplace Installer
#
# Downloads and installs Zoom Workplace from Zoom's official source.
# License: https://explore.zoom.us/en/terms/
#
# H-007 Phase B migration: records the install footprint via the
# /usr/share/igos/helpers/helper-lib.sh API.

set -e

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

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

# K21.F: signed-Release verification chain against Zoom's official apt
# repository. Source-of-truth for the latest .deb filename + sha256 is
# the apt-style metadata under /dists/stable/ on Zoom's official apt
# repo at https://zoom.us/linux/download/prod (suite `stable`,
# component `main`). Do NOT add fallback repositories or pivot to the
# unsigned direct .deb URL without a security review: alternate
# download sources are a supply-chain vector.
ZOOM_APT_BASE="https://zoom.us/linux/download/prod"
ZOOM_DIST="stable"
ZOOM_PKG_NAME="zoom"
ZOOM_KEYRING="/usr/share/igos/helpers/keyrings/zoom-keyring.gpg"
TMPDIR=$(mktemp -d)
# BLOCKING-D fix (2026-05-19): register TMPDIR cleanup via the
# helper-lib's IGOS_HELPER_USER_CLEANUP env var instead of `trap EXIT`.
# Installing a native trap would collide with the one igos_helper_init
# installs for partial-manifest sidecar emission (bash trap-replace
# semantics; no native composition).
IGOS_HELPER_USER_CLEANUP="rm -rf $TMPDIR"

echo ""
echo "  InterGenOS Zoom Workplace Installer"
echo "  ====================================="
echo ""
echo "  Zoom Workplace is proprietary software."
echo "  License: https://explore.zoom.us/en/terms/"
echo ""

if [ "$(id -u)" -ne 0 ]; then
    echo "  ERROR: Run via 'sudo pkm install-helper zoom' instead."
    echo "  Direct invocation bypasses pkm's manifest ingestion;"
    echo "  pkm files/verify/remove will not see the installed files."
    exit 1
fi

# EULA acceptance gate. The acceptance record at /var/lib/intergen/legal/
# is intentionally NOT manifest-tracked: pkm remove leaves it in place
# so a subsequent reinstall reads existing acceptance and skips the
# re-prompt (Row F decision 2026-05-19; ffmpeg-nonfree canonical
# K21.C pattern). The record IS captured in pkm's operation log as
# transparency content via the post_install_action below.
if [ -f "$ACCEPTANCE_FILE" ]; then
    echo "  Acceptance already recorded at $ACCEPTANCE_FILE"
    echo "  Proceeding to install."
else
    echo ""
    echo "  Do you accept Zoom's license terms above and authorize"
    echo "  installing Zoom Workplace 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": "zoom",
  "version": "1.0",
  "payload_license": "LicenseRef-Zoom-Terms-of-Service",
  "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 "zoom"

# K21.C: capture the consent event in pkm's operation log as
# transparency content. The acceptance JSON itself is intentionally
# NOT manifest-tracked (see EULA acceptance gate above).
igos_helper_record_post_install_action \
    "User accepted Zoom license terms (acceptance artifact at $ACCEPTANCE_FILE)"

echo "  Finding latest Zoom Workplace release in signed apt metadata..."
LATEST=$(igos_helper_find_latest_deb_in_packages "$ZOOM_PKG_NAME" "$ZOOM_APT_BASE" "$ZOOM_DIST")
if [ -z "$LATEST" ]; then
    echo "  ERROR: Could not locate the zoom package in the official Zoom"
    echo "         apt Packages metadata at ${ZOOM_APT_BASE}/dists/${ZOOM_DIST}/"
    echo ""
    echo "  This may be a transient outage. Retry later, or check"
    echo "  https://zoom.us/download?os=linux for service advisories."
    echo ""
    echo "  This installer intentionally uses ONLY Zoom's official"
    echo "  distribution. Do not patch in alternate sources without"
    echo "  security review."
    exit 1
fi
DEB_NAME=$(echo "$LATEST" | cut -d'|' -f1)
ZOOM_VERSION=$(echo "$LATEST" | cut -d'|' -f2)
POOL_PATH=$(echo "$LATEST" | cut -d'|' -f3)
igos_helper_set_version "${ZOOM_VERSION:-unknown}"

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

# K21.F: refuse install if signed-Release verification fails. This
# checks InRelease GPG signature (against the pinned keyring at
# ${ZOOM_KEYRING}) + Packages sha256 (against InRelease) + .deb
# sha256 (against Packages). Any step failure refuses install.
echo "  Verifying signed-Release integrity chain..."
if ! igos_helper_verify_deb_via_signed_release \
    "$DEB_NAME" \
    "$TMPDIR/zoom.deb" \
    "$ZOOM_APT_BASE" \
    "$ZOOM_KEYRING" \
    "$ZOOM_DIST"; then
    echo ""
    echo "  ERROR: Signed-Release verification FAILED for ${DEB_NAME}."
    echo "  Refusing to install. The downloaded .deb did not match the"
    echo "  vendor's signed apt-repo metadata. This may indicate network"
    echo "  corruption, a man-in-the-middle attack, or a vendor key"
    echo "  rotation. Do NOT extract the .deb manually."
    exit 1
fi

echo "  Extracting..."
cd "$TMPDIR"
ar x zoom.deb
tar xf data.tar.xz 2>/dev/null || tar xf data.tar.gz 2>/dev/null || tar --zstd -xf data.tar.zst 2>/dev/null

echo "  Installing to /opt/zoom/..."
# Zoom's .deb installs the client under /opt/zoom and ships its .desktop
# launcher + icon under usr/share.
cp -a opt/zoom /opt/
cp -a usr/share/applications/* /usr/share/applications/ 2>/dev/null || true
cp -a usr/share/icons/* /usr/share/icons/ 2>/dev/null || true
cp -a usr/share/pixmaps/* /usr/share/pixmaps/ 2>/dev/null || true

# The .deb's Zoom.desktop uses Exec=/usr/bin/zoom (created by the .deb's
# postinst). We do not run postinst, so create the launcher symlink
# ourselves — otherwise the menu entry's Exec target is dead.

# H-007: record everything deposited under /opt/zoom + the system-wide
# .desktop launcher + icons.
while IFS= read -r f; do
    igos_helper_record_file "$f"
done < <(find /opt/zoom -type f -o -type l 2>/dev/null)
for f in /usr/share/applications/Zoom*.desktop /usr/share/applications/zoom*.desktop; do
    if [ -f "$f" ]; then
        igos_helper_record_file "$f"
    fi
done
while IFS= read -r f; do
    [ -f "$f" ] && igos_helper_record_file "$f"
done < <(find /usr/share/icons /usr/share/pixmaps -name 'Zoom*' -o -name 'zoom*' -type f 2>/dev/null)

ln -sf /opt/zoom/ZoomLauncher /usr/bin/zoom
igos_helper_record_symlink /usr/bin/zoom /opt/zoom/ZoomLauncher

igos_helper_record_dep 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 "  Zoom Workplace installed successfully!"
echo "  Run: zoom"
echo ""
