#!/bin/sh
# Red Ribbon's AppImage entry point. scripts/package/linux.sh fills in the
# @...@ values when it builds the AppImage.
#
# WPE WebKit starts its helper processes (WPEWebProcess, WPENetworkProcess)
# and finds its data at absolute paths compiled into it, which can't point
# into an AppImage: it's mounted somewhere new each run. The packaging
# overwrote those paths with a same-length placeholder under /tmp. Here
# each user gets a copy of the bundled WPE in their cache with the
# placeholder set to a link of their own in /tmp, and that link points at
# the copy. The copy is made once per build and outlives the mount.
#
# The libraries stay replaceable (LGPL 2.1 §6): put your own
# libWPEWebKit-2.0.so.1 in the cache copy's lib/ folder, or a folder with
# it first in LD_LIBRARY_PATH. See usr/share/doc/ribbon/WPE-WEBKIT-SOURCE.txt.
set -eu

here="${APPDIR:-$(dirname "$(readlink -f "$0")")}"

# ---- Preflight: can this Linux run Red Ribbon? -------------------------------------
# Runs before anything else, on any Linux (plain POSIX sh, coreutils only), so a system
# that can't run the app hears why in words instead of a loader error. RIBBON_SKIP_PREFLIGHT=1
# skips it. The floors (docs/release.md, Linux AppImage):
#   - x86_64: the only build.
#   - Linux 3.17: WebKit's sandbox launcher hands bubblewrap its arguments through a
#     sealed memfd (memfd_create, 3.17), and Rust's and glibc's own floors (3.2) are lower.
#     Every distribution with a new enough glibc ships a far newer kernel, so this mostly
#     catches old containers and odd environments. (bubblewrap also needs unprivileged
#     user namespaces, a setting rather than a version, so it isn't checked here.)
#   - glibc @GLIBC_MIN@: the newest glibc symbol version anything in the AppImage uses
#     (linux.sh reads it from the binaries); the build runs on Debian 13 for that reason.
#   - a Wayland session: the Linux build draws through Wayland only.
#   - the libraries left to the system (graphics drivers, Wayland, fontconfig, GLib,
#     GStreamer, ...): the host's own loader is asked to resolve every binary, so a
#     missing library or one too old for a symbol we use is named exactly.
glibc_min='@GLIBC_MIN@'
kernel_min='3.17'
works_on='Debian 13 or newer, Ubuntu 25.04 or newer, Fedora 42 or newer, Arch Linux, openSUSE Tumbleweed, or another distribution from 2025 on'

# version_ge A B: A >= B, comparing up to three dot-separated numbers.
version_ge() {
    a=$1; b=$2
    for _ in 1 2 3; do
        x=${a%%.*}; y=${b%%.*}
        x=${x%%[!0-9]*}; y=${y%%[!0-9]*}
        x=${x:-0}; y=${y:-0}
        [ "$x" -gt "$y" ] && return 0
        [ "$x" -lt "$y" ] && return 1
        case "$a" in *.*) a=${a#*.} ;; *) a=0 ;; esac
        case "$b" in *.*) b=${b#*.} ;; *) b=0 ;; esac
    done
    return 0
}

# Shows the message where the person will see it: the terminal if there is one,
# else a dialog from whatever the desktop has.
tell() {
    printf '%s\n' "$1" >&2
    [ -t 2 ] && return 0
    title="Red Ribbon can't start"
    if command -v zenity >/dev/null 2>&1 && zenity --error --title="$title" --no-markup --width=520 --text="$1" 2>/dev/null; then :
    elif command -v kdialog >/dev/null 2>&1 && kdialog --title "$title" --error "$1" 2>/dev/null; then :
    elif command -v notify-send >/dev/null 2>&1 && notify-send -u critical "$title" "$1" 2>/dev/null; then :
    elif command -v xmessage >/dev/null 2>&1; then xmessage -center "$title

$1" 2>/dev/null || :
    fi
}

stop() {
    tell "Red Ribbon can't start on this computer:

$1

To start it anyway (for example to test), run it with RIBBON_SKIP_PREFLIGHT=1."
    exit 1
}

# Distribution packages for a library left to the system: "debian|fedora|arch".
package_of() {
    case "$1" in
        libEGL.so*|libGLESv2.so*|libGL.so*|libOpenGL.so*) echo 'libegl1|libglvnd-egl|libglvnd' ;;
        libgbm.so*) echo 'libgbm1|mesa-libgbm|mesa' ;;
        libdrm.so*) echo 'libdrm2|libdrm|libdrm' ;;
        libwayland-*) echo 'libwayland-client0 libwayland-egl1|libwayland-client libwayland-egl|wayland' ;;
        libxkbcommon.so*) echo 'libxkbcommon0|libxkbcommon|libxkbcommon' ;;
        libxkbcommon-x11.so*) echo 'libxkbcommon-x11-0|libxkbcommon-x11|libxkbcommon-x11' ;;
        libxcb.so*) echo 'libxcb1|libxcb|libxcb' ;;
        libfontconfig.so*) echo 'libfontconfig1|fontconfig|fontconfig' ;;
        libfreetype.so*) echo 'libfreetype6|freetype|freetype2' ;;
        libglib-2.0.so*|libgobject-2.0.so*|libgio-2.0.so*|libgmodule-2.0.so*) echo 'libglib2.0-0t64|glib2|glib2' ;;
        libsoup-3.0.so*) echo 'libsoup-3.0-0|libsoup3|libsoup3' ;;
        libgstreamer-1.0.so*|libgstbase-1.0.so*) echo 'libgstreamer1.0-0|gstreamer1|gstreamer' ;;
        libgstcodecparsers-1.0.so*|libgstmpegts-1.0.so*|libgsttranscoder-1.0.so*|libgstwebrtc-1.0.so*) echo 'libgstreamer-plugins-bad1.0-0|gstreamer1-plugins-bad-free-libs|gst-plugins-bad-libs' ;;
        libgstgl-1.0.so*) echo 'libgstreamer-gl1.0-0|gstreamer1-plugins-base|gst-plugins-base-libs' ;;
        libgst*) echo 'libgstreamer-plugins-base1.0-0|gstreamer1-plugins-base|gst-plugins-base-libs' ;;
        libenchant-2.so*) echo 'libenchant-2-2|enchant2|enchant' ;;
        libepoxy.so*) echo 'libepoxy0|libepoxy|libepoxy' ;;
        libharfbuzz*) echo 'libharfbuzz0b libharfbuzz-icu0|harfbuzz harfbuzz-icu|harfbuzz harfbuzz-icu' ;;
        libjpeg.so*) echo 'libjpeg62-turbo|libjpeg-turbo|libjpeg-turbo' ;;
        libpng16.so*) echo 'libpng16-16t64|libpng|libpng' ;;
        libwebp*.so*|libsharpyuv.so*) echo 'libwebp7 libwebpdemux2 libwebpmux3|libwebp|libwebp' ;;
        liblcms2.so*) echo 'liblcms2-2|lcms2|lcms2' ;;
        libtasn1.so*) echo 'libtasn1-6|libtasn1|libtasn1' ;;
        libsqlite3.so*) echo 'libsqlite3-0|sqlite-libs|sqlite' ;;
        libbrotli*) echo 'libbrotli1|libbrotli|brotli' ;;
        libgcrypt.so*|libgpg-error.so*) echo 'libgcrypt20|libgcrypt|libgcrypt' ;;
        libseccomp.so*) echo 'libseccomp2|libseccomp|libseccomp' ;;
        libsystemd.so*) echo 'libsystemd0|systemd-libs|systemd-libs' ;;
        libgnutls.so*) echo 'libgnutls30t64|gnutls|gnutls' ;;
        libdbus-1.so*) echo 'libdbus-1-3|dbus-libs|dbus' ;;
        libudev.so*) echo 'libudev1|systemd-libs|systemd-libs' ;;
        libasound.so*) echo 'libasound2t64|alsa-lib|alsa-lib' ;;
        libvulkan.so*) echo 'libvulkan1|vulkan-loader|vulkan-icd-loader' ;;
        libcairo.so*) echo 'libcairo2|cairo|cairo' ;;
        libstdc++.so*|libgcc_s.so*) echo 'libstdc++6|libstdc++|gcc-libs' ;;
        libatomic.so*) echo 'libatomic1|libatomic|gcc-libs' ;;
        *) echo '' ;;
    esac
}

preflight() {
    arch="$(uname -m)"
    [ "$arch" = x86_64 ] || stop "This copy of Red Ribbon is for 64-bit Intel and AMD PCs (x86_64), and this computer is $arch."

    kernel="$(uname -r)"
    version_ge "$kernel" "$kernel_min" ||
        stop "Linux (the kernel) is version $kernel here; Red Ribbon needs $kernel_min or newer. Update your distribution, or use one of: $works_on."

    loader=/lib64/ld-linux-x86-64.so.2
    if [ ! -e "$loader" ]; then
        if [ -e /lib/ld-musl-x86_64.so.1 ]; then
            stop "This Linux uses the musl C library (Alpine, Void musl, Chimera, ...). Red Ribbon is built for the GNU C library (glibc) that most distributions use: $works_on. On a musl system, a glibc container (for example Distrobox with Debian 13) runs it."
        fi
        stop "This Linux has no GNU C library loader ($loader). Red Ribbon is built for glibc systems: $works_on."
    fi

    glibc="$(getconf GNU_LIBC_VERSION 2>/dev/null || :)"
    glibc="${glibc#glibc }"
    case "$glibc" in [0-9]*) ;; *) glibc="$("$loader" --version 2>/dev/null | sed -n '1s/.*[^0-9.]\([0-9][0-9]*\.[0-9][0-9]*\)[^0-9]*$/\1/p')" ;; esac
    if [ -n "$glibc" ] && ! version_ge "$glibc" "$glibc_min"; then
        stop "This Linux's C library (glibc) is version $glibc; Red Ribbon needs $glibc_min or newer. It runs on $works_on."
    fi

    if [ -z "${WAYLAND_DISPLAY:-}" ]; then
        if [ -n "${DISPLAY:-}" ]; then
            stop "You're logged in to an X11 session. Red Ribbon for Linux runs on Wayland only: log out, choose the Wayland session at the login screen (GNOME and KDE Plasma offer it, and it's the default on most distributions now), and start Red Ribbon again."
        fi
        stop "There's no graphical Wayland session here (WAYLAND_DISPLAY isn't set). Start Red Ribbon from a desktop session running on Wayland, such as GNOME or KDE Plasma."
    fi
    case "$WAYLAND_DISPLAY" in /*) sock="$WAYLAND_DISPLAY" ;; *) sock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$WAYLAND_DISPLAY" ;; esac
    [ -S "$sock" ] || stop "The Wayland session named by WAYLAND_DISPLAY ($sock) isn't there. Start Red Ribbon from inside your desktop session."

    # Every binary we ship, resolved the way the system will load it: the bundled
    # libraries first (as AppRun's LD_LIBRARY_PATH will put them), then the system's.
    missing=''; old=''; undefined=''
    for bin in "$here/usr/bin/ribbon" "$here"/wpe/libexec/*/WPE*Process "$here/wpe/lib/libWPEWebKit-2.0.so.1"; do
        [ -f "$bin" ] || continue
        # What `ldd -r` does: the loader in trace mode lists every library, "not found" ones
        # included (--list stops at the first one missing), and with every symbol bound now
        # it names the ones no installed library has, which is how a library too old for us
        # shows when it has no symbol versions (libsoup, GStreamer, ...). It loads nothing.
        out="$(LD_TRACE_LOADED_OBJECTS=1 LD_WARN=yes LD_BIND_NOW=yes LD_LIBRARY_PATH="$here/wpe/lib" "$loader" "$bin" 2>&1 || :)"
        missing="$missing $(printf '%s\n' "$out" | sed -n 's/^[[:space:]]*\([^[:space:]]*\) => not found.*/\1/p' | tr '\n' ' ')"
        old="$old $(printf '%s\n' "$out" | sed -n "s/.*version \`\([^']*\)' not found (required by \([^)]*\)).*/\1/p" | tr '\n' ' ')"
        undefined="$undefined $(printf '%s\n' "$out" | sed -n 's/^[[:space:]]*undefined symbol: \([^[:space:]]*\).*/\1/p' | tr '\n' ' ')"
    done
    # A missing library leaves its symbols undefined too: those only count when nothing is.
    # shellcheck disable=SC2086 # a symbol list, split on purpose
    [ -n "$(printf '%s' "$missing" | tr -d ' ')" ] || old="$old $(printf '%s\n' $undefined | sort -u | head -8 | tr '\n' ' ')"
    # Word lists split on purpose (sonames and version names have no glob characters).
    # shellcheck disable=SC2086
    missing="$(printf '%s\n' $missing | sort -u | tr '\n' ' ')"
    # shellcheck disable=SC2086
    old="$(printf '%s\n' $old | sort -u | tr '\n' ' ')"
    missing="${missing% }"; old="${old% }"
    missing="${missing# }"; old="${old# }"
    if [ -n "$missing" ] || [ -n "$old" ]; then
        deb=''; fed=''; arc=''
        for lib in $missing; do
            p="$(package_of "$lib")"
            [ -n "$p" ] || continue
            deb="$deb ${p%%|*}"; rest="${p#*|}"; fed="$fed ${rest%%|*}"; arc="$arc ${rest#*|}"
        done
        # shellcheck disable=SC2086 # a package list, split on purpose
        dedup() { printf '%s\n' $1 | sort -u | tr '\n' ' '; }
        msg=''
        [ -z "$missing" ] || msg="These libraries Red Ribbon uses aren't installed: $missing."
        if [ -n "$old" ]; then
            # Which library a missing symbol belongs to, by its prefix.
            libs=''
            for sym in $old; do
                case "$sym" in
                    GLIBC_*) l='the C library (glibc)' ;;
                    GLIBCXX_*|CXXABI_*) l='the C++ library (libstdc++)' ;;
                    gst_*|GST_*) l='GStreamer' ;;
                    soup_*|SOUP_*) l='libsoup' ;;
                    g_*|glib_*) l='GLib' ;;
                    Fc*) l='fontconfig' ;;
                    FT_*) l='FreeType' ;;
                    hb_*) l='HarfBuzz' ;;
                    wl_*) l='Wayland' ;;
                    xkb_*) l='xkbcommon' ;;
                    gbm_*) l='Mesa (GBM)' ;;
                    egl*|EGL_*) l='EGL' ;;
                    enchant_*) l='Enchant' ;;
                    *) l='' ;;
                esac
                case ", $libs, " in *", $l, "*) ;; *) [ -z "$l" ] || libs="${libs:+$libs, }$l" ;; esac
            done
            msg="${msg:+$msg

}Some installed libraries are older than Red Ribbon needs${libs:+ ($libs)}: it looked for $old and didn't find them. Update your system (for example: sudo apt full-upgrade, sudo dnf upgrade, sudo pacman -Syu); Red Ribbon runs on $works_on."
        fi
        if [ -n "$deb$fed$arc" ]; then
            id=''; like=''
            if [ -r /etc/os-release ]; then
                id="$(sed -n 's/^ID=//p' /etc/os-release | tr -d '"')"
                like="$(sed -n 's/^ID_LIKE=//p' /etc/os-release | tr -d '"')"
            fi
            case " $id $like " in
                *" debian "*|*" ubuntu "*) msg="$msg

Install them with: sudo apt install $(dedup "$deb")" ;;
                *" fedora "*|*" rhel "*) msg="$msg

Install them with: sudo dnf install $(dedup "$fed")" ;;
                *" arch "*) msg="$msg

Install them with: sudo pacman -S --needed $(dedup "$arc")" ;;
                *) msg="$msg

Install them with your package manager. Debian / Ubuntu: sudo apt install $(dedup "$deb"); Fedora: sudo dnf install $(dedup "$fed"); Arch: sudo pacman -S --needed $(dedup "$arc")" ;;
            esac
        fi
        stop "$msg"
    fi

    # The interface draws with the system's fonts and can't start without one of the
    # families gpui falls back to (its text_system.rs list). A minimal install can have
    # none of them: Arch's default font package is GNU FreeFont, which isn't on the list.
    families='DejaVu Sans|Noto Sans|Cantarell|Ubuntu|Adwaita Sans|Arial|Helvetica|Segoe UI'
    font=''
    if command -v fc-list >/dev/null 2>&1; then
        font="$(fc-list : family 2>/dev/null | tr ',' '\n' | grep -E -i -m 1 "^($families)\$" || :)"
    else
        for dir in /usr/share/fonts /usr/local/share/fonts "${XDG_DATA_HOME:-$HOME/.local/share}/fonts" "$HOME/.fonts"; do
            [ -d "$dir" ] || continue
            font="$(find "$dir" -type f \( -iname 'DejaVuSans*' -o -iname 'NotoSans-*' -o -iname 'Cantarell*' -o -iname 'Ubuntu*' \
                -o -iname 'AdwaitaSans*' -o -iname 'Arial*' -o -iname 'Helvetica*' -o -iname 'segoeui*' \) 2>/dev/null | head -n 1)"
            [ -z "$font" ] || break
        done
    fi
    if [ -z "$font" ]; then
        id=''; like=''
        if [ -r /etc/os-release ]; then
            id="$(sed -n 's/^ID=//p' /etc/os-release | tr -d '"')"
            like="$(sed -n 's/^ID_LIKE=//p' /etc/os-release | tr -d '"')"
        fi
        case " $id $like " in
            *" debian "*|*" ubuntu "*) how='sudo apt install fonts-dejavu-core' ;;
            *" fedora "*|*" rhel "*) how='sudo dnf install dejavu-sans-fonts' ;;
            *" arch "*) how='sudo pacman -S --needed ttf-dejavu' ;;
            *) how='your package manager (DejaVu or Noto fonts, for example)' ;;
        esac
        stop "Red Ribbon draws its windows with one of these fonts, and none of them is installed: DejaVu Sans, Noto Sans, Cantarell, Ubuntu, Adwaita Sans or Arial.

Install them with: $how"
    fi

    # Not fatal: without them WebKit's web content runs unsandboxed (it says so).
    for tool in bwrap xdg-dbus-proxy; do
        command -v "$tool" >/dev/null 2>&1 ||
            printf 'Red Ribbon: %s is not installed, so web pages in browser tabs run without their sandbox (install bubblewrap and xdg-dbus-proxy).\n' "$tool" >&2
    done
}
[ "${RIBBON_SKIP_PREFLIGHT:-}" = 1 ] || preflight
# ---- End of the preflight ---------------------------------------------------------

tag='@TAG@'
build='@BUILD_ID@'
placeholder='@PLACEHOLDER@'
template="/tmp/.rbw-XXXXXXXXXX-$tag"
uid="$(id -u)"

# Same length as the placeholder: a fixed-width uid in place of the X's.
link="/tmp/.rbw-$(printf '%010d' "$uid")-$tag${placeholder#"$template"}"
cache="${XDG_CACHE_HOME:-$HOME/.cache}/ribbon/appimage/$tag-$build"

if [ ! -f "$cache/.ready" ]; then
    echo "Red Ribbon: copying WebKit into $cache (once per version)" >&2
    mkdir -p "${cache%/*}"
    # Built aside and moved into place whole, so a Red Ribbon starting at the
    # same moment never sees half a copy.
    tmp="$(mktemp -d "$cache.XXXXXX")"
    cp -a "$here/wpe/." "$tmp/"
    pattern="$(printf '%s' "$placeholder" | sed 's/[.]/\\./g')"
    grep -rlF "$placeholder" "$tmp" | while IFS= read -r f; do
        LC_ALL=C sed -i "s|$pattern|$link|g" "$f"
    done
    touch "$tmp/.ready"
    mv -T "$tmp" "$cache" 2>/dev/null || rm -rf "$tmp"
    # Copies of earlier builds of this WPE version.
    for old in "${cache%/*}/$tag"-*; do
        case "$old" in "$cache" | "$cache".*) ;; *) rm -rf "$old" ;; esac
    done
fi

# /tmp is shared: refuse a link someone else made in our name.
owner() { stat -c %u "$1" 2>/dev/null || echo none; }
if [ -e "$link" ] || [ -L "$link" ]; then
    if [ ! -L "$link" ] || [ "$(owner "$link")" != "$uid" ]; then
        echo "Red Ribbon: $link exists and isn't a link of yours; remove it and start Red Ribbon again." >&2
        exit 1
    fi
fi
ln -sfn "$cache" "$link"
if [ "$(readlink "$link")" != "$cache" ] || [ "$(owner "$link")" != "$uid" ]; then
    echo "Red Ribbon: couldn't set up $link" >&2
    exit 1
fi

# After any folders already there, so a WPE of your own wins.
LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$cache/lib"
export LD_LIBRARY_PATH
exec "$here/usr/bin/ribbon" "$@"
