#!/bin/bash
# InterGenOS Discord Installer
#
# Downloads and installs Discord from official source.
# License: https://discord.com/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/discord-1.0-accepted.json"

DISCORD_URL="https://discord.com/api/download?platform=linux&format=tar.gz"
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 Discord Installer"
echo "  =============================="
echo ""
echo "  Discord is proprietary software."
echo "  License: https://discord.com/terms"
echo ""
echo "  K21.F supply-chain trust posture (operator-ratified Option B"
echo "  2026-05-21):"
echo ""
echo "    Discord does NOT publish a signed apt repository. This helper"
echo "    downloads Discord's tarball over HTTPS from discord.com's CDN"
echo "    with NO cryptographic signature verification of the tarball"
echo "    contents. The trust chain is HTTPS-only -- TLS certificate"
echo "    chain to discord.com. If Discord's CDN were compromised or a"
echo "    TLS certificate were stolen, this helper would have NO way to"
echo "    detect a substituted tarball."
echo ""
echo "    All 6 other vendor helpers (brave + chrome + edge + vscode +"
echo "    spotify + claude-code) use stronger trust anchors via K21.E"
echo "    apt-Release signature chains + K21.F npm-registry signature"
echo "    verification. Discord is the supply-chain exception by"
echo "    operator decision 2026-05-21: the alternative trust anchor"
echo "    (Snap Store cryptographic signatures via 'snap install') was"
echo "    explicitly REJECTED by the project-canonical no-snapd"
echo "    directive."
echo ""
echo "    Documentation IS the discipline (Holy Grail Rule 1: no"
echo "    security trade-off for convenience -- the gap is NAMED here,"
echo "    not hidden). You are running this helper explicitly via"
echo "    'pkm install-helper discord'; proceeding records your"
echo "    acceptance of BOTH the license terms AND awareness of the"
echo "    HTTPS-only supply-chain trust posture."
echo ""

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

# EULA + K21.F-Option-B trust-gap 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. K21.F Option B (operator-direct
# 2026-05-21): combined acceptance covers both license terms AND
# awareness of the HTTPS-only supply-chain trust posture; the JSON
# fields trust_anchor + trust_chain_caveat document the gap inline.
if [ -f "$ACCEPTANCE_FILE" ]; then
    echo "  Acceptance already recorded at $ACCEPTANCE_FILE"
    echo "  Proceeding to install."
else
    echo "  Do you accept Discord's license terms above AND understand"
    echo "  the HTTPS-only trust-posture disclosure above? Authorize"
    echo "  installing Discord 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": "discord",
  "version": "1.0",
  "payload_license": "LicenseRef-Discord-ToS",
  "trust_anchor": "HTTPS-only (no cryptographic signature on tarball)",
  "trust_chain_caveat": "Discord does not publish a signed apt repository; the Snap-Store alternative is rejected by the project-canonical no-snapd directive (operator-direct 2026-05-21); the K21.F Option B trust-gap disclosure was presented and accepted at install time.",
  "k21_f_option": "B",
  "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 "discord"

# K21.C + K21.F Option B: 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). The recorded action explicitly cites BOTH license terms
# AND K21.F Option B trust-gap acknowledgment for cold-read
# auditability.
igos_helper_record_post_install_action \
    "User accepted Discord license terms + K21.F Option B HTTPS-only trust-gap disclosure (acceptance artifact at $ACCEPTANCE_FILE)"

# Discord's tarball doesn't have a version stamp in the URL; extract
# from the build info file inside the tarball after extract.
igos_helper_set_version "latest"

echo "  Downloading Discord..."
wget -q --show-progress -O "$TMPDIR/discord.tar.gz" "$DISCORD_URL"

echo "  Extracting..."
rm -rf /opt/discord
tar -xzf "$TMPDIR/discord.tar.gz" -C /opt/
# The tarball's top-level dir is "Discord" (capital), but the bundled launcher
# script resolves its updater bootstrap at /opt/discord/updater_bootstrap
# (lowercase) and the binary is the lowercase script /opt/discord/discord —
# normalize the install dir to lowercase or Discord cannot find its bootstrap
# and fails to start (the old capital /opt/Discord/Discord path no longer
# exists in Discord's updater-based packaging).
[ -d /opt/Discord ] && mv /opt/Discord /opt/discord

# H-007: record everything deposited under /opt/discord plus the
# .desktop launcher created below.
while IFS= read -r f; do
    igos_helper_record_file "$f"
done < <(find /opt/discord -type f -o -type l 2>/dev/null)

echo "  Creating launcher..."
ln -sf /opt/discord/discord /usr/bin/discord
igos_helper_record_symlink /usr/bin/discord /opt/discord/discord

cat > /usr/share/applications/discord.desktop << 'DESKEOF'
[Desktop Entry]
Name=Discord
Comment=All-in-one voice and text chat
Exec=/opt/discord/discord
Icon=/opt/discord/discord.png
Type=Application
Categories=Network;InstantMessaging;
StartupWMClass=discord
DESKEOF
igos_helper_record_file /usr/share/applications/discord.desktop

igos_helper_record_dep glibc

igos_helper_commit

echo ""
echo "  Discord installed successfully!"
echo "  Run: discord"
echo ""
