set -euo pipefail apex_install() ( local base='https://apexclient.org' theme='' answer='' manager='' work='' package='' candidate='' server='' service='' browser='' browser_package='' browser_home='' local -ar release_keys=('_vq6ApiWWjD0ZktuIRK8mYo2WaMIL7LYzBiFotUXQ8A') local mode='' options_given='' ui_fd='' ui_pid='' ui_status='' browser_cache='' program='' stage_number=0 stage_total=7 local manual_packages='' nix_host='' libc='' runtime_path="${LD_LIBRARY_PATH:-}" local nix_fhs='' fhs_program='' local -a apex_run=() local -a required=() missing=() optional=() extras=() running() { local state='' { state="$(< "/proc/$1/stat")"; } 2>/dev/null || return 1 state="${state##*) }" [[ -n "$state" && "${state%% *}" != Z ]] } ui_alive() { [[ -n "$ui_pid" ]] && running "$ui_pid"; } ui_send() { [[ -n "$ui_fd" ]] && ui_alive || return 0 local line='' field for field in "$@"; do field="${field//[$'\t\r\n']/ }" line+="${line:+$'\t'}$field" done ( printf '%s\n' "$line" >&"$ui_fd" ) 2>/dev/null || true } ui_wait() { [[ -n "$ui_pid" ]] || return 0 ui_status=0 wait "$ui_pid" || ui_status=$? ui_pid='' if [[ -n "$ui_fd" ]]; then exec {ui_fd}>&-; ui_fd=''; fi } fail() { printf '\n%s\n' "$*" >&2 if ui_alive; then ui_send finish fail "$*" printf '%s\n' 'Close the installer window to finish.' >&2 ui_wait fi return 1 } ui_check() { [[ -n "$ui_pid" ]] || return 0 ui_alive && return 0 ui_wait if (( ui_status == 11 )); then printf '\n%s\n' "Installation was cancelled in the installer window. $1" >&2 exit 1 fi if (( ui_status == 12 )); then printf '\n%s\n' 'The installer window could not be shown, so installation continues here.' else printf '\n%s\n' 'The installer window closed, so installation continues here.'; fi mode=shell return 0 } stage() { stage_number=$((stage_number + 1)) [[ -z "$mode" ]] || printf '\n\033[1m[%d/%d] %s\033[0m\n' "$stage_number" "$stage_total" "$2" ui_send stage "$1" active "$2" } stage_done() { ui_send stage "$1" done "$2"; } confirm() { printf '\n%s [y/N] ' "$1" > /dev/tty || return 1 IFS= read -r answer < /dev/tty || return 1 [[ "$answer" == [yY] || "$answer" == [yY][eE][sS] ]] } (( $# == 0 )) || options_given=1 while (( $# )); do case "$1" in --server) [[ -z "$service$theme" ]] || { fail 'Unsupported installer option.'; return 1; }; service=1; shift ;; --no-system-packages) manual_packages=1; shift ;; --wsl-theme) [[ -z "$service$theme" ]] || { fail 'Unsupported installer option.'; return 1; } theme="${2:-}" [[ "$theme" == dark || "$theme" == light ]] || { fail 'Invalid window theme.'; return 1; } [[ -n "${WSL_DISTRO_NAME:-}" ]] || { fail 'This option is for WSL only.'; return 1; } shift 2 ;; --browser) [[ -z "$browser" ]] || { fail 'Unsupported installer option.'; return 1; } browser="${2:-}" [[ "$browser" == system || "$browser" == apex ]] || { fail 'Use --browser system to install WebKitGTK from your distribution, or --browser apex to download Apex'"'"'s copy.'; return 1; } shift 2 ;; *) fail 'Unsupported installer option.'; return 1 ;; esac done if [[ -z "$mode" && -z "$options_given" && -t 1 && -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]] && { : < /dev/tty > /dev/tty; } 2>/dev/null; then printf '\n%s\n %s\n %s\n' 'How do you want to install Apex?' '1) Graphical installer' '2) Interactive shell installer' > /dev/tty while :; do printf '%s' 'Choose 1 or 2 [1]: ' > /dev/tty IFS= read -r answer < /dev/tty || answer=1 case "$answer" in ''|1) mode=graphical; break ;; 2) mode=shell; break ;; esac done fi [[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { fail 'Apex requires x86-64 Linux.'; return 1; } [[ "$(id -u)" != 0 ]] || { fail 'Run this installer as your normal user, without sudo. Finish Ubuntu user setup first if needed.'; return 1; } [[ -n "${HOME:-}" && "$HOME" == /* && -d "$HOME" && -w "$HOME" ]] || { fail 'Your home folder is unavailable or not writable.'; return 1; } if ! libc="$(getconf GNU_LIBC_VERSION 2>/dev/null)" || [[ ! "$libc" =~ ^glibc\ ([0-9]+)\.([0-9]+)$ ]]; then fail 'Apex needs a glibc Linux environment. On Alpine or Void musl, use a supported glibc installation.' return 1 fi if (( BASH_REMATCH[1] < 2 || (BASH_REMATCH[1] == 2 && BASH_REMATCH[2] < 35) )); then fail 'Apex requires glibc 2.35 or newer. Update your distribution before installing.' return 1 fi if ! compgen -G '/dev/dri/renderD*' >/dev/null; then server=1; fi browser_home="$HOME/.local/share/lib" local data_home="${XDG_DATA_HOME:-}" state_home="${XDG_STATE_HOME:-}" program_hint="$HOME/.local/bin/apex" [[ "$data_home" == /* ]] || data_home="$HOME/.local/share" [[ "$state_home" == /* ]] || state_home="$HOME/.local/state" [[ ! -f "$HOME/.apex-bin/apex" ]] || program_hint="$HOME/.apex-bin/apex" if [[ -n "$mode" ]]; then stage system 'Checking this system' printf ' %-13s %s\n' 'Program:' "$program_hint" 'Data:' "$data_home/apex" 'Logs:' "$state_home/apex" 'Menu entry:' "$data_home/applications/apex.desktop" stage packages 'System packages' fi apt_installed() { dpkg-query -W -f='${db:Status-Status} ${Architecture}\n' "$1" 2>/dev/null | grep -Eq '^installed (amd64|all)$'; } local os_release=/etc/os-release distro_id='' distro_like='' distro_variant='' key value family='' local -a distro_ancestry=() [[ -r "$os_release" ]] || os_release=/usr/lib/os-release if [[ -r "$os_release" ]]; then while IFS='=' read -r key value || [[ -n "$key" ]]; do case "$key" in ID|ID_LIKE|VARIANT_ID) ;; *) continue ;; esac value="${value%$'\r'}" if [[ "$value" == \"*\" || "$value" == \'*\' ]]; then value="${value:1:-1}"; fi case "$key" in ID) distro_id="$value" ;; ID_LIKE) distro_like="$value" ;; VARIANT_ID) distro_variant="$value" ;; esac done < "$os_release" fi IFS=$' \t' read -r -a distro_ancestry <<< "$distro_like" for value in "$distro_id" "${distro_ancestry[@]}"; do case "$value" in debian|ubuntu|linuxmint|pop|elementary|zorin|kali|raspbian) family=apt ;; arch|manjaro|endeavouros|cachyos|garuda|artix) family=pacman ;; fedora|rhel|centos|rocky|almalinux|nobara|bazzite|silverblue) family=dnf ;; opensuse|opensuse-*|suse|sles|sled|sle-micro|sl-micro) family=zypper ;; void) family=xbps ;; nixos|steamos|gentoo|funtoo|solus|alpine) family=manual ;; *) continue ;; esac break done if [[ -e /etc/NIXOS || "$distro_id" == nixos ]]; then nix_host=1 manual_packages=1 local nix_libraries="${NIX_LD_LIBRARY_PATH_x86_64_linux:-${NIX_LD_LIBRARY_PATH:-}}" if [[ -n "$nix_libraries" ]]; then runtime_path="$nix_libraries${runtime_path:+:$runtime_path}" fi if [[ -z "$nix_libraries" ]] && command -v nix >/dev/null 2>&1; then nix_fhs=1; fi fi local transactional='' if [[ "$family" == zypper ]]; then case "$distro_id/$distro_variant" in opensuse-microos/*|opensuse-leap-micro/*|opensuse-aeon/*|opensuse-kalpa/*|sle-micro/*|sl-micro/*|*/aeon|*/kalpa|*/microos) transactional=1 ;; esac if command -v transactional-update >/dev/null 2>&1 && findmnt -n -T /usr -o VFS-OPTIONS 2>/dev/null | grep -Eq '(^|,)ro(,|$)'; then transactional=1 fi fi if [[ -e /run/ostree-booted || "$distro_id" == steamos || "$distro_id" == bazzite || "$distro_id" == silverblue || "$distro_variant" == silverblue || "$distro_variant" == kinoite || -n "$transactional" ]]; then manual_packages=1 fi local runtime_entry local -a runtime_entries=() IFS=: read -r -a runtime_entries <<< "$runtime_path" runtime_path='' for runtime_entry in "${runtime_entries[@]}"; do [[ -n "$runtime_entry" && "$runtime_entry" != "$browser_home" && ! "$runtime_entry" -ef "$browser_home" ]] || continue runtime_path+="${runtime_path:+:}$runtime_entry" done if [[ -n "$manual_packages" ]]; then manager=manual elif [[ "$family" == apt ]] && command -v apt-get >/dev/null 2>&1; then manager=apt required=(ca-certificates curl python3 openssl libdbus-1-3 libegl1 libgles2 libx11-6 libwayland-client0 libwayland-egl1 libxkbcommon0 libfontconfig1 libharfbuzz0b zlib1g libbrotli1 libgcc-s1 libstdc++6 libglib2.0-bin xdg-utils desktop-file-utils) for package in libglib2.0-0 libpng16-16 libelf1; do if apt_installed "$package"; then required+=("$package") elif apt_installed "${package}t64"; then required+=("${package}t64") else candidate="$package" if apt-cache show "${package}t64" >/dev/null 2>&1; then candidate="${package}t64"; fi required+=("$candidate") fi done if [[ -n "$theme" || -n "$server" ]]; then required+=(libegl-mesa0 libgl1-mesa-dri); fi browser_package=libwebkit2gtk-4.1-0 optional=(libsecret-1-0) if [[ -n "$theme" ]]; then optional+=(libdecor-0-0 libdecor-0-plugin-1-gtk mesa-utils); fi elif [[ "$family" == pacman ]] && command -v pacman >/dev/null 2>&1; then manager=pacman required=(ca-certificates curl python openssl dbus glib2 libglvnd mesa gcc-libs libx11 wayland libxkbcommon fontconfig harfbuzz libpng libelf zlib brotli xdg-utils desktop-file-utils) browser_package=webkit2gtk-4.1 optional=(libsecret) elif [[ "$family" == dnf ]] && command -v dnf >/dev/null 2>&1; then manager=dnf required=(ca-certificates curl python3 openssl dbus-libs glib2 libglvnd-egl libglvnd-gles mesa-libEGL libgcc libstdc++ libX11 libwayland-client libwayland-egl libxkbcommon fontconfig harfbuzz libpng elfutils-libelf zlib libbrotli xdg-utils desktop-file-utils) if [[ -n "$server" ]]; then required+=(mesa-dri-drivers); fi browser_package=webkit2gtk4.1 optional=(libsecret) elif [[ "$family" == zypper ]] && command -v zypper >/dev/null 2>&1; then manager=zypper required=(ca-certificates curl python3 openssl libdbus-1-3 libgio-2_0-0 libglib-2_0-0 libgobject-2_0-0 libglvnd Mesa-libEGL1 libgcc_s1 libstdc++6 libX11-6 libwayland-client0 libwayland-egl1 libxkbcommon0 fontconfig libharfbuzz0 libpng16-16 libelf1 libz1 libbrotlidec1 xdg-utils desktop-file-utils) if [[ -n "$server" ]]; then required+=(Mesa-dri); fi browser_package=libwebkit2gtk-4_1-0 optional=(libsecret-1-0) elif [[ "$family" == xbps ]] && command -v xbps-install >/dev/null 2>&1 && command -v xbps-query >/dev/null 2>&1; then manager=xbps required=(ca-certificates curl python3 openssl dbus-libs glib libglvnd libgcc libstdc++ libX11 wayland libxkbcommon fontconfig libharfbuzz libpng libelf zlib brotli xdg-utils desktop-file-utils) if [[ -n "$server" ]]; then required+=(mesa-dri); fi browser_package=libwebkit2gtk41 optional=(libsecret) else manager=manual fi nix_fhs_setup() { local profile_bin='' candidate='' for candidate in "$HOME/.nix-profile/bin" "${XDG_STATE_HOME:-$HOME/.local/state}/nix/profile/bin"; do [[ ! -x "$candidate/apex-fhs" ]] || { profile_bin="$candidate"; break; } done if [[ -z "$profile_bin" ]]; then printf '%s\n' 'NixOS keeps libraries in the Nix store, so Apex runs inside a small environment that provides them.' \ 'This adds one package, apex-fhs, to your own Nix profile. It needs no administrator access and changes no system file.' \ 'Remove it later with: nix profile remove apex-fhs' confirm 'Add apex-fhs to your Nix profile now?' || { fail 'Nothing was changed. To use Apex on NixOS, add the Apex flake module (programs.apex.enable = true;) or enable programs.nix-ld with the libraries it lists, then run this installer again.' return 1 } local expression scratch scratch="$(mktemp -d)" || { fail 'A temporary folder could not be created.'; return 1; } expression='let pkgs = (builtins.getFlake "nixpkgs").legacyPackages.x86_64-linux; in pkgs.buildFHSEnv { name = "apex-fhs"; targetPkgs = _: map pkgs.lib.getLib (with pkgs; [ stdenv.cc.cc.lib dbus glib libglvnd vulkan-loader wayland libxkbcommon libx11 fontconfig freetype harfbuzz libpng zlib brotli elfutils libxcursor libxext libxi libxfixes libxrandr libxscrnsaver libayatana-appindicator libsecret libwebp pipewire libpulseaudio alsa-lib webkitgtk_4_1 gtk3 libsoup_3 ]); runScript = pkgs.writeShellScript "apex-fhs-run" "p=$HOME/.nix-profile/bin/apex-fhs; [ -x \"$p\" ] || p=\${XDG_STATE_HOME:-$HOME/.local/state}/nix/profile/bin/apex-fhs; export APEX_LAUNCH_PREFIX=\"$p\"; exec \"$@\""; }' local fallback="${expression/(builtins.getFlake \"nixpkgs\").legacyPackages.x86_64-linux/import \{ system = \"x86_64-linux\"; \}}" if ! nix --extra-experimental-features 'nix-command flakes' profile install --impure --expr "$expression" > "$scratch/nix.log" 2>&1 && ! nix --extra-experimental-features 'nix-command flakes' profile install --impure --expr "$fallback" > "$scratch/nix.log" 2>&1; then tail -n 8 "$scratch/nix.log" >&2 rm -rf "$scratch" fail 'Nix could not add apex-fhs. Fix the error shown above, or use the Apex flake module, then run this installer again.' return 1 fi rm -rf "$scratch" for candidate in "$HOME/.nix-profile/bin" "${XDG_STATE_HOME:-$HOME/.local/state}/nix/profile/bin"; do [[ ! -x "$candidate/apex-fhs" ]] || { profile_bin="$candidate"; break; } done fi [[ -n "$profile_bin" ]] || { fail 'apex-fhs was added but could not be found in your Nix profile.'; return 1; } fhs_program="$profile_bin/apex-fhs" apex_run=("$fhs_program") export APEX_LAUNCH_PREFIX="$fhs_program" printf '%s\n' 'Apex will run inside apex-fhs.' } if [[ "$manager" == manual ]]; then printf '%s\n' 'Using system libraries already available to this user. Apex will leave system packages alone.' browser_package='WebKitGTK 4.1' if [[ -n "$nix_fhs" ]]; then nix_fhs_setup || return 1 elif [[ -n "$nix_host" ]]; then printf '%s\n' 'On NixOS, enable programs.nix-ld and add WebKitGTK 4.1 and the required runtime libraries to programs.nix-ld.libraries, then rebuild and sign in again.' elif [[ -n "$transactional" ]]; then printf '%s\n' 'On transactional openSUSE or SUSE Micro, install any missing system libraries with transactional-update and reboot into the new snapshot.' fi fi installed() { case "$manager" in apt) apt_installed "$1" ;; pacman) pacman -Q "$1" >/dev/null 2>&1 ;; dnf|zypper) rpm -q --whatprovides "$1" >/dev/null 2>&1 ;; xbps) xbps-query -p state "$1" 2>/dev/null | grep -qx installed ;; manual) [[ "$1" == "$browser_package" ]] && command -v python3 >/dev/null && LD_LIBRARY_PATH="$runtime_path" python3 -c 'import ctypes; ctypes.CDLL("libwebkit2gtk-4.1.so.0")' >/dev/null 2>&1 ;; esac } offered() { case "$manager" in apt) apt-cache show "$1" >/dev/null 2>&1 ;; pacman) pacman -Si -- "$1" >/dev/null 2>&1 ;; dnf) dnf -q info -- "$1" >/dev/null 2>&1 ;; zypper) zypper --non-interactive --quiet search --match-exact -- "$1" >/dev/null 2>&1 ;; xbps) xbps-query -R -p pkgver "$1" >/dev/null 2>&1 ;; esac } install_packages() { command -v sudo >/dev/null 2>&1 || return 1 case "$manager" in apt) sudo apt-get update && sudo apt-get install -y -- "$@" ;; pacman) sudo pacman -S --needed -- "$@" < /dev/tty ;; dnf) sudo dnf install -y -- "$@" ;; zypper) sudo zypper --non-interactive install -- "$@" ;; xbps) sudo xbps-install -Sy "$@" ;; esac } install_command() { case "$manager" in apt) printf 'sudo apt-get install %s' "$*" ;; pacman) printf 'sudo pacman -S --needed %s' "$*" ;; dnf) printf 'sudo dnf install %s' "$*" ;; zypper) printf 'sudo zypper install %s' "$*" ;; xbps) printf 'sudo xbps-install -S %s' "$*" ;; esac } if [[ "$manager" != manual && -n "$theme" && "$browser" != apex ]]; then required+=("$browser_package"); fi for package in "${required[@]}"; do installed "$package" || missing+=("$package"); done if (( ${#missing[@]} )); then printf '\nMissing runtime packages:\n %s\n' "${missing[*]}" [[ -z "$mode" ]] || printf '%s\n %s\n' 'To install them yourself instead, run:' "$(install_command "${missing[@]}")" confirm 'Install these packages?' || { fail 'No packages were installed. Install the missing packages before continuing.'; return 1; } command -v sudo >/dev/null 2>&1 || { fail 'sudo is unavailable. Ask your administrator to install the listed packages, then rerun this installer.'; return 1; } case "$manager" in apt) sudo apt-get update || return 1 for index in "${!missing[@]}"; do package="${missing[index]}" if [[ "$package" == libglib2.0-0 || "$package" == libpng16-16 || "$package" == libelf1 ]] && apt-cache show "${package}t64" >/dev/null 2>&1; then missing[index]="${package}t64"; fi done sudo apt-get install -y -- "${missing[@]}" ;; pacman) sudo pacman -S --needed -- "${missing[@]}" < /dev/tty ;; dnf) sudo dnf install -y -- "${missing[@]}" ;; zypper) sudo zypper --non-interactive install -- "${missing[@]}" ;; xbps) install_packages "${missing[@]}" ;; esac || { fail 'Package installation did not finish. Your Apex data was kept.'; return 1; } for package in "${missing[@]}"; do installed "$package" || { fail "Required package is still unavailable: $package"; return 1; }; done fi if [[ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]] && command -v gdbus >/dev/null 2>&1 && [[ -n "${DBUS_SESSION_BUS_ADDRESS:-}" || -S "${XDG_RUNTIME_DIR:-/nonexistent}/bus" ]]; then local names names="$(gdbus call --session --timeout 5 --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.ListNames 2>/dev/null; gdbus call --session --timeout 5 --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.ListActivatableNames 2>/dev/null)" || true if [[ -n "$names" && "$names" != *"'org.freedesktop.secrets'"* ]]; then if [[ "${XDG_CURRENT_DESKTOP:-}" == *KDE* ]]; then printf '\n%s\n' 'No password store answers on this desktop, so Apex cannot protect saved sign-ins yet. Turn on KDE Wallet in System Settings, then sign out and back in.' else printf '\n%s\n' 'No password store answers on this desktop, so Apex cannot protect saved sign-ins yet. GNOME Keyring provides one; sign out and back in after installing it.' if [[ "$manager" != manual ]] && ! installed gnome-keyring; then optional+=(gnome-keyring); fi fi fi fi if [[ -z "$browser" && -f "$browser_home/apex-webkit-runtime.json" && ! -L "$browser_home/apex-webkit-runtime.json" ]] && ! installed "$browser_package"; then printf '\n%s\n' "Keeping Apex's WebKitGTK copy in $browser_home. Rerun this installer with --browser system to use your distribution's package instead." browser=apex fi if [[ -n "$mode" && -z "$browser" ]] && ! installed "$browser_package"; then if offered "$browser_package"; then printf '\n%s\n' 'Apex needs WebKitGTK 4.1 for sign-in and web pages.' while [[ -z "$browser" ]]; do printf ' %s\n' "1) Install $browser_package from your distribution now (uses sudo)" '2) Install it yourself, then check again' "3) Let Apex download and manage its own copy in $browser_home" printf '%s' 'Choose 1, 2 or 3 [1]: ' IFS= read -r answer < /dev/tty || answer=3 case "$answer" in ''|1) if install_packages "$browser_package" && installed "$browser_package"; then browser=system else printf '\n%s\n' "$browser_package was not installed. Choose another option."; fi ;; 2) printf '\n%s\n %s\n%s' 'Run this command in another terminal:' "$(install_command "$browser_package")" 'Press Enter when it has finished. ' IFS= read -r answer < /dev/tty || true if installed "$browser_package"; then printf '%s\n' "$browser_package is installed."; browser=system else printf '\n%s\n' "$browser_package is still not installed. Choose an option."; fi ;; 3) browser=apex ;; esac done else printf '\n%s\n' "This distribution does not offer WebKitGTK 4.1, so Apex will download its own copy into $browser_home." browser=apex fi fi if [[ "$browser" != apex ]] && ! installed "$browser_package"; then if offered "$browser_package"; then printf '\n%s\n %s\n' 'Apex needs WebKitGTK 4.1 for sign-in and web pages:' "$browser_package" if [[ "$browser" == system ]] || confirm 'Install it from your distribution? Answer no to let Apex download its own copy instead.'; then if install_packages "$browser_package" && installed "$browser_package"; then browser=system elif [[ "$browser" == system ]]; then fail "WebKitGTK 4.1 could not be installed. Install $browser_package yourself, or rerun this installer with --browser apex to download Apex's copy." return 1 else printf '%s\n' "The package could not be installed, so Apex will download its own copy into $browser_home." browser=apex fi else browser=apex fi elif [[ "$browser" == system ]]; then fail "This distribution does not offer $browser_package. Rerun this installer with --browser apex to download Apex's copy." return 1 else printf '\n%s\n' "This distribution does not offer WebKitGTK 4.1, so Apex will download its own copy into $browser_home." browser=apex fi elif [[ "$browser" != apex ]]; then browser=system fi if [[ "$browser" == apex && "$manager" != manual ]] && ! installed glib-networking; then printf '\n%s\n' 'Secure web pages also need glib-networking from your distribution.' if confirm 'Install glib-networking now?'; then install_packages glib-networking || printf '%s\n' 'glib-networking was not installed. Sign-in pages may not load until it is.'; fi fi for package in "${optional[@]}"; do installed "$package" || extras+=("$package"); done if (( ${#extras[@]} )); then printf '\nRecommended for browser sign-in, protected saved sign-ins and window decorations:\n %s\n' "${extras[*]}" if confirm 'Install these optional packages?'; then case "$manager" in apt) if sudo apt-get update; then local -a available=() for package in "${extras[@]}"; do if apt-cache show "$package" >/dev/null 2>&1; then available+=("$package") else printf '%s\n' "Optional package is not available in this distribution: $package"; fi done if (( ${#available[@]} )); then sudo apt-get install -y -- "${available[@]}"; fi else false; fi ;; pacman) sudo pacman -S --needed -- "${extras[@]}" < /dev/tty ;; dnf) sudo dnf install -y -- "${extras[@]}" ;; zypper) sudo zypper --non-interactive install -- "${extras[@]}" ;; xbps) install_packages "${extras[@]}" ;; esac || printf '%s\n' 'Optional setup did not finish. Apex can still be installed.' fi fi command -v python3 >/dev/null 2>&1 || { fail 'Python 3 is required to check the download.'; return 1; } local python python="$(type -P python3)" || { fail 'The Python 3 executable could not be found.'; return 1; } command -v curl >/dev/null 2>&1 || { fail 'curl is required to download Apex.'; return 1; } command -v openssl >/dev/null 2>&1 || { fail 'OpenSSL is required to verify the Apex release signature.'; return 1; } work="$(mktemp -d)" || return 1 trap 'rm -rf -- "$work"' EXIT local expected='' size='' local -a transfer=(--fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 --connect-timeout 20 --retry 2 --retry-delay 1 --retry-max-time 90) error_line() { local line='' line="$(tail -n 1 -- "$work/error" 2>/dev/null)" || true printf '%s' "${line:-$1}" } transfer_run() { local id="$1" total="$2" destination="$3" pid='' seen=0 status=0 shift 3 if [[ -n "$id" && -n "$ui_fd" ]]; then curl --silent --show-error "$@" -o "$destination" & pid=$! while running "$pid"; do if ! ui_alive; then kill "$pid" 2>/dev/null || true wait "$pid" 2>/dev/null || true return 130 fi seen="$(stat -c %s -- "$destination" 2>/dev/null)" || seen=0 ui_send bytes "$id" "$seen" "$total" sleep 0.25 done wait "$pid" || status=$? return "$status" fi if [[ -n "$id" && -n "$mode" ]]; then curl --progress-bar "$@" -o "$destination" return fi curl --silent --show-error "$@" -o "$destination" } fetch() { local destination="$1" limit="$2" timeout="$3" url="$4" id="${5:-}" result=0 local -a options=("${transfer[@]}" --max-time "$timeout" --max-filesize "$limit") while :; do result=0 transfer_run "$id" "$limit" "$destination" "${options[@]}" "$url" || result=$? (( result == 130 )) && [[ -n "$ui_pid" ]] || break ui_check 'Nothing else was changed.' done (( result != 0 )) || return 0 case "$result" in 16|92) printf '%s\n' 'The download connection was interrupted. Retrying with a compatible connection...' transfer_run "$id" "$limit" "$destination" --http1.1 "${options[@]}" "$url" ;; *) return "$result" ;; esac } webkit_stage() { if [[ "$browser" == apex ]]; then printf '\n%s\n' "Checking Apex's WebKitGTK copy..." ui_send detail webkit "Checking Apex's WebKitGTK copy" fetch "$work/browser.json" 65536 60 "$base/v1/runtimes/webkit" || { fail "Apex's WebKitGTK copy is unavailable right now. Install $browser_package from your distribution, or try again later."; return 1; } python3 - "$work/browser.json" > "$work/browser-expected" 2> "$work/error" <<'PY' || { fail "$(error_line "Apex's WebKitGTK copy could not be checked.")"; return 1; } import json, re, sys try: with open(sys.argv[1], encoding='utf-8') as file: info = json.load(file) except (OSError, ValueError): raise SystemExit("Apex's WebKitGTK copy could not be checked. Please try again later.") from None if not isinstance(info, dict) or info.get('available') is not True: raise SystemExit("Apex's WebKitGTK copy is not available yet. Install WebKitGTK 4.1 from your distribution instead.") if info.get('format') != 'apex-webkit-runtime-v1' or info.get('platform') != 'linux-x86_64': raise SystemExit("Apex's WebKitGTK copy is not compatible with this installer.") if not isinstance(info.get('sha256'), str) or not re.fullmatch('[0-9a-f]{64}', info['sha256']): raise SystemExit("Apex's WebKitGTK copy has an invalid checksum.") size = info.get('bytes') if type(size) is not int or not 1024 <= size <= 805306368: raise SystemExit("Apex's WebKitGTK copy has an invalid size.") version = info.get('version') if not isinstance(version, str) or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,40}', version): raise SystemExit("Apex's WebKitGTK copy has an invalid version.") print(info['sha256']) print(size) print(version) PY local browser_sha browser_size browser_version { IFS= read -r browser_sha; IFS= read -r browser_size; IFS= read -r browser_version; } < "$work/browser-expected" printf '%s\n' "Downloading Apex's WebKitGTK $browser_version copy..." ui_send detail webkit "Downloading WebKitGTK $browser_version" fetch "$work/browser.tar.xz" "$browser_size" 1800 "$base/download/webkit-runtime" webkit || { fail "The WebKitGTK download did not finish. Nothing was changed."; return 1; } ui_send detail webkit "Verifying and unpacking into $browser_home" ui_send bytes webkit 0 0 if ! "$python" - "$work/browser.tar.xz" "$browser_sha" "$browser_size" "$browser_version" "$browser_home" "$runtime_path" 2> "$work/error" <<'PY' import hashlib, json, os, posixpath, secrets, shutil, stat, subprocess, sys, tarfile archive, expected, size, version, home = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4], sys.argv[5] library, marker = 'libwebkit2gtk-4.1.so.0', 'apex-webkit-runtime.json' system_only = ('ld-linux', 'libc.so', 'libm.so', 'libdl.so', 'libpthread', 'librt.so', 'libstdc++', 'libgcc_s', 'libglib-2.0', 'libgobject-2.0', 'libgio-2.0', 'libgmodule-2.0', 'libgthread-2.0') def stop(text): raise SystemExit(text + ' Nothing was installed.') digest = hashlib.sha256() try: with open(archive, 'rb') as stream: for block in iter(lambda: stream.read(1048576), b''): digest.update(block) if os.path.getsize(archive) != size or digest.hexdigest() != expected: stop('The WebKitGTK download could not be verified.') except OSError: stop('The WebKitGTK download could not be read.') uid = os.getuid() def owned_directory(path): info = os.lstat(path) if not stat.S_ISDIR(info.st_mode) or info.st_uid != uid: stop(path + ' is not a folder that belongs to you.') if info.st_mode & 0o022: os.chmod(path, stat.S_IMODE(info.st_mode) & ~0o022) os.makedirs(home, mode=0o755, exist_ok=True) owned_directory(home) entries, total = [], 0 try: with tarfile.open(archive, 'r:xz') as bundle: members = bundle.getmembers() if len(members) > 6000: stop('The WebKitGTK download has too many files.') names = set() for member in members: name = posixpath.normpath(member.name) parts = name.split('/') if (member.name.startswith('/') or name in ('', '.') or '..' in parts or '\\' in name or name == marker or parts[0].startswith('.') or any(ord(c) < 32 for c in name)): stop('The WebKitGTK download contains an unsafe path.') if name in names: stop('The WebKitGTK download contains a repeated path.') if parts[-1].startswith(system_only): stop('The WebKitGTK download contains a system library it must not replace.') names.add(name) if member.isdir(): entries.append(('dir', name, None)) elif member.isfile(): total += member.size if total > 2147483648: stop('The WebKitGTK download is too large.') entries.append(('file', name, member)) elif member.issym(): target = member.linkname resolved = posixpath.normpath(posixpath.join(posixpath.dirname(name), target)) if target.startswith('/') or resolved == '..' or resolved.startswith('../') or resolved == '.': stop('The WebKitGTK download contains an unsafe link.') entries.append(('link', name, target)) else: stop('The WebKitGTK download contains an unsupported file type.') if library not in names: stop('The WebKitGTK download does not contain ' + library + '.') stage = os.path.join(home, '.apex-webkit-' + secrets.token_hex(8)) os.mkdir(stage, 0o700) try: for kind, name, data in sorted(entries, key=lambda item: item[1].count('/')): target = os.path.join(stage, name) os.makedirs(os.path.dirname(target), mode=0o755, exist_ok=True) if kind == 'dir': os.makedirs(target, mode=0o755, exist_ok=True) elif kind == 'link': os.symlink(data, target) else: mode = 0o755 if data.mode & 0o111 else 0o644 descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, mode) with os.fdopen(descriptor, 'wb') as out, bundle.extractfile(data) as source: shutil.copyfileobj(source, out, 1048576) out.flush() os.fsync(out.fileno()) os.chmod(target, mode) probe_env = dict(os.environ) probe_env['LD_LIBRARY_PATH'] = stage + (':' + sys.argv[6] if sys.argv[6] else '') try: probe = subprocess.run([sys.executable, '-c', 'import ctypes, sys; ctypes.CDLL(sys.argv[1])', os.path.join(stage, library)], env=probe_env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) except subprocess.TimeoutExpired: stop("Apex's WebKitGTK copy timed out while loading. The existing browser was kept.") if probe.returncode: stop("Apex's WebKitGTK copy could not load on this system. The existing browser was kept. Install WebKitGTK 4.1 from your distribution and retry.") previous = [] try: with open(os.path.join(home, marker), encoding='utf-8') as file: previous = [item for item in json.load(file).get('files', []) if isinstance(item, str)] except (OSError, ValueError, AttributeError): previous = [] installed = [name for kind, name, _ in entries if kind != 'dir'] for kind, name, _ in entries: final = os.path.join(home, name) try: is_directory = stat.S_ISDIR(os.lstat(final).st_mode) except FileNotFoundError: continue if is_directory != (kind == 'dir'): stop(final + ' is in the way; move it away and run this installer again.') for name in sorted(set(previous) - set(installed), key=lambda item: -item.count('/')): clean = posixpath.normpath(name) if clean.startswith(('/', '../')) or clean in ('', '.', '..', marker): continue path = os.path.join(home, clean) try: info = os.lstat(path) if (stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)) and info.st_uid == uid: os.unlink(path) except OSError: pass for kind, name, _ in sorted(entries, key=lambda item: item[1].count('/')): final = os.path.join(home, name) parent = os.path.dirname(final) if parent != home: os.makedirs(parent, mode=0o755, exist_ok=True) owned_directory(parent) if kind == 'dir': os.makedirs(final, mode=0o755, exist_ok=True) owned_directory(final) continue os.replace(os.path.join(stage, name), final) record = {'format': 'apex-webkit-runtime-v1', 'version': version, 'sha256': expected, 'files': installed} temporary = os.path.join(home, '.' + marker + '.' + secrets.token_hex(4)) descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o644) with os.fdopen(descriptor, 'w', encoding='utf-8') as file: json.dump(record, file) file.flush() os.fsync(file.fileno()) os.replace(temporary, os.path.join(home, marker)) finally: shutil.rmtree(stage, ignore_errors=True) except (OSError, tarfile.TarError, EOFError) as error: raise SystemExit('Apex could not install its WebKitGTK copy: ' + (getattr(error, 'strerror', None) or type(error).__name__) + '.') from None PY then fail "$(error_line "Apex could not install its WebKitGTK copy.")" return 1 fi fi local browser_path="$runtime_path" [[ "$browser" != apex ]] || browser_path="$browser_home${runtime_path:+:$runtime_path}" ui_send detail webkit 'Checking that WebKitGTK loads' LD_LIBRARY_PATH="$browser_path" python3 -c 'import ctypes; ctypes.CDLL("libwebkit2gtk-4.1.so.0")' > "$work/browser-check" 2>&1 || { sed -n '$p' "$work/browser-check" >&2 if [[ "$browser" == apex ]]; then fail "Apex's WebKitGTK copy was installed but could not load. Install $browser_package from your distribution instead, or report this with the line above." else fail "WebKitGTK 4.1 is installed but could not load. Reinstall $browser_package, or rerun this installer with --browser apex."; fi return 1 } if [[ "$browser" == system && -f "$browser_home/apex-webkit-runtime.json" && ! -L "$browser_home/apex-webkit-runtime.json" ]]; then python3 - "$browser_home" <<'PY' || true import json, os, posixpath, stat, sys home = sys.argv[1] marker = os.path.join(home, 'apex-webkit-runtime.json') try: with open(marker, encoding='utf-8') as file: files = [item for item in json.load(file).get('files', []) if isinstance(item, str)] except (OSError, ValueError, AttributeError): raise SystemExit(0) uid = os.getuid() for name in sorted(files, key=lambda item: -item.count('/')): clean = posixpath.normpath(name) if clean.startswith(('/', '../')) or clean in ('', '.', '..'): continue path = os.path.join(home, clean) try: info = os.lstat(path) if (stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)) and info.st_uid == uid: os.unlink(path) except OSError: pass os.unlink(marker) print("Removed Apex's WebKitGTK copy; your distribution's WebKitGTK is used instead.") PY fi if [[ "$browser" == apex ]]; then stage_done webkit "Apex's copy in $browser_home"; else stage_done webkit 'From your distribution'; fi } release_stage() { printf '\n%s\n' 'Checking the current Apex release...' fetch "$work/release.json" 65536 60 "$base/v1/releases/latest" || { fail 'Release information is unavailable. Try again later.'; return 1; } if ! "$python" - "$work/release.json" "$work" "${release_keys[@]}" > "$work/expected" 2> "$work/error" <<'PY' import base64, json, pathlib, re, subprocess, sys, time def unique(pairs): result = {} for key, value in pairs: if key in result: raise ValueError('duplicate JSON field') result[key] = value return result def decode(value, size): if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', value): raise ValueError('invalid base64') result = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4)) if len(result) != size or base64.urlsafe_b64encode(result).decode().rstrip('=') != value: raise ValueError('invalid base64') return result try: with open(sys.argv[1], encoding='utf-8') as file: envelope = json.load(file, object_pairs_hook=unique) if not isinstance(envelope, dict) or set(envelope) != {'payload', 'signature'}: raise ValueError('invalid release envelope') payload = envelope['payload'] fields = {'format', 'platform', 'version', 'sequence', 'filename', 'size', 'sha256', 'published_at', 'expires_at'} if not isinstance(payload, dict) or set(payload) != fields: raise ValueError('invalid release payload') signature = decode(envelope['signature'], 64) keys = [decode(key, 32) for key in sys.argv[3:]] if not 1 <= len(keys) <= 2 or len(set(keys)) != len(keys): raise ValueError('invalid installer trust keys') except (OSError, ValueError, TypeError, KeyError): raise SystemExit('Signed release information could not be read. Your current installation was kept.') from None work = pathlib.Path(sys.argv[2]) manifest, sig, pin = (work / name for name in ('release-payload', 'release-signature', 'release-pin.der')) try: manifest.write_bytes(json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True, allow_nan=False).encode('utf-8')) sig.write_bytes(signature) for key in keys: pin.write_bytes(bytes.fromhex('302a300506032b6570032100') + key) check = subprocess.run(['openssl', 'pkeyutl', '-verify', '-pubin', '-keyform', 'DER', '-inkey', str(pin), '-rawin', '-in', str(manifest), '-sigfile', str(sig)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) if check.returncode == 0: break else: raise SystemExit('The Apex release signature could not be verified. Your current installation was kept.') except (OSError, ValueError, subprocess.TimeoutExpired): raise SystemExit('OpenSSL could not check the Apex release signature. Your current installation was kept.') from None if payload['format'] != 'apex-release-v1' or payload['platform'] != 'linux-x86_64': raise SystemExit('The signed release is not compatible with this installer.') if (not isinstance(payload['version'], str) or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?', payload['version']) or type(payload['sequence']) is not int or payload['sequence'] < 1): raise SystemExit('Invalid signed release version or sequence.') digest = payload['sha256'] if not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest) or payload['filename'] != f'apex-{digest}.bin': raise SystemExit('Invalid signed release file identity.') size = payload['size'] if type(size) is not int or not 1024 <= size <= 134217728: raise SystemExit('Invalid signed release size.') now = time.time() published, expiry = payload['published_at'], payload['expires_at'] if type(published) is not int or type(expiry) is not int or not 0 < published < expiry or published > now + 300 or expiry <= now: raise SystemExit('This release information is expired or dated incorrectly. Check your clock or try again later.') print(digest) print(size) PY then fail "$(error_line 'Release information could not be checked.')" return 1 fi { IFS= read -r expected; IFS= read -r size; } < "$work/expected" printf '%s\n' 'Downloading Apex...' fetch "$work/apex" "$size" 600 "$base/download" release || { fail 'The download did not finish. Your current installation was kept.'; return 1; } python3 - "$work/apex" "$expected" "$size" 2> "$work/error" <<'PY' || { fail "$(error_line 'The download could not be verified. Nothing was installed. Please retry.')"; return 1; } import hashlib, pathlib, sys file = pathlib.Path(sys.argv[1]) try: digest = hashlib.sha256() with file.open('rb') as stream: header = stream.read(20) stream.seek(0) for block in iter(lambda: stream.read(1048576), b''): digest.update(block) size = file.stat().st_size except OSError: raise SystemExit('The download could not be read. Your current installation was kept.') from None if size != int(sys.argv[3]) or digest.hexdigest() != sys.argv[2]: raise SystemExit('The download could not be verified. Nothing was installed. Please retry.') if len(header) < 20 or header[:6] != b'\x7fELF\x02\x01' or header[18:20] != b'\x3e\x00': raise SystemExit('The download is not an x86-64 Linux executable.') PY chmod 700 "$work/apex" if [[ -z "$nix_host" ]] && command -v ldd >/dev/null && { ! ldd "$work/apex" > "$work/libraries" 2>&1 || grep -q 'not found' "$work/libraries"; }; then printf '\n%s\n' 'Some system libraries are missing or too old:' >&2 cat "$work/libraries" >&2 fail 'Update the listed runtime libraries and try again. Your current Apex installation was kept.' return 1 fi if ! ${apex_run[@]+"${apex_run[@]}"} "$work/apex" --help > "$work/help" 2>&1 && [[ -n "$nix_host" && -z "$fhs_program" ]] && grep -q 'cannot open shared object file' "$work/help" && command -v nix >/dev/null 2>&1; then printf '%s\n' 'Your NixOS setup is missing libraries Apex needs:' >&2 grep 'cannot open shared object file' "$work/help" | head -n 3 >&2 nix_fhs_setup || return 1 fi if ! ${apex_run[@]+"${apex_run[@]}"} "$work/apex" --help > "$work/help" 2>&1; then tail -n 5 "$work/help" >&2 if [[ -n "$nix_host" && -z "$fhs_program" ]]; then printf '%s\n' 'Add the missing libraries with programs.nix-ld.libraries (pkgs.dbus.lib is a common one), or install Nix so this installer can add apex-fhs, then run it again.' >&2 fi fail 'The downloaded Apex could not start on this system. Fix the error shown above and retry. Your current installation was kept.' return 1 fi stage_done release 'Downloaded and verified' } ui_start() { if ! grep -q -- '--install-ui' "$work/help"; then printf '\n%s\n' 'This Apex release has no installer window, so installation continues here.' mode=shell return 0 fi if ! mkfifo -m 600 "$work/progress" || ! exec {ui_fd}<> "$work/progress"; then ui_fd='' printf '\n%s\n' 'The installer window could not be opened, so installation continues here.' mode=shell return 0 fi ${apex_run[@]+"${apex_run[@]}"} "$work/apex" --install-ui < "$work/progress" > "$work/installer.log" 2>&1 {ui_fd}>&- & ui_pid=$! printf '\n%s\n' 'The installer window is open. Progress is also shown here.' ui_send apex-install 1 ui_send path program "$program_hint" ui_send path data "$data_home/apex" ui_send path logs "$state_home/apex" ui_send path menu "$data_home/applications/apex.desktop" [[ "$browser" != apex ]] || ui_send path webkit "$browser_home" ui_send stage system done 'Checking this system' ui_send stage packages done 'System packages' ui_send stage release done 'Downloading and verifying Apex' ui_send stage webkit pending 'WebKitGTK' ui_send stage install pending 'Installing Apex' ui_send stage menu pending 'Menu entry' ui_send stage requirements pending 'Worker requirements' } if [[ "$mode" == graphical ]]; then stage release 'Downloading and verifying Apex' release_stage ui_start stage webkit 'WebKitGTK' webkit_stage else stage release 'Downloading and verifying Apex' release_stage stage webkit 'WebKitGTK' webkit_stage fi ui_check 'Nothing was installed.' local -a install_options=(--install) if [[ "$mode" == shell ]] && grep -q -- '--browser-cache' "$work/help"; then browser_cache=off ! grep -qx 'browser_keep_ready=1' "$data_home/apex/settings/settings.conf" 2>/dev/null || browser_cache=on printf '\n%s\n%s' 'Cache In-App Browser: uses slightly more memory to help the in-app browser open faster.' "Turn it on? [$([[ "$browser_cache" == on ]] && printf 'Y/n' || printf 'y/N')] " if IFS= read -r answer < /dev/tty; then case "$answer" in [yY]|[yY][eE][sS]) browser_cache=on ;; [nN]|[nN][oO]) browser_cache=off ;; esac install_options+=(--browser-cache "$browser_cache") else printf '\n' fi fi stage install 'Installing Apex' ${apex_run[@]+"${apex_run[@]}"} "$work/apex" "${install_options[@]}" || { fail 'Apex installation did not finish. Your saved accounts and settings were kept.'; return 1; } stage_done install 'Program copied and registered' ui_check 'Apex was installed, but its menu entry was not updated. Run this installer again to finish.' stage menu 'Menu entry' local desktop_library='' [[ "$browser" != apex ]] || desktop_library="$browser_home" python3 - "$data_home/applications/apex.desktop" "$theme" "$expected" "$HOME" "$desktop_library" > "$work/program" <<'PY' || { fail 'Apex was installed, but its program file could not be checked. Run this installer again.'; return 1; } import hashlib, os, pathlib, re, stat, sys, tempfile entry, theme, expected, home, library = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] def note(text): print(text, file=sys.stderr) def unquote(value): out, index = [], 0 while index < len(value): character = value[index] if character == '\\' and index + 1 < len(value): following = value[index + 1] out.append({'s': ' ', 'n': '\n', 't': '\t', 'r': '\r', '\\': '\\'}.get(following, '\\' + following)) index += 2 continue out.append(character) index += 1 return re.sub(r'\\([\\"`$])', r'\1', ''.join(out)).replace('%%', '%') lines = [] if entry.is_file() and not entry.is_symlink(): try: lines = entry.read_text(encoding='utf-8').splitlines() except (OSError, UnicodeDecodeError): lines = [] candidates = [] for line in lines: found = re.match(r'^Exec=.*?"((?:[^"\\]|\\.)*)" %u$', line) if found: candidates.append(unquote(found.group(1))) candidates += [home + '/.local/bin/apex', home + '/.apex-bin/apex'] def installed(path): try: info = os.lstat(path) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or not info.st_mode & stat.S_IXUSR: return False digest = hashlib.sha256() with open(path, 'rb') as stream: for block in iter(lambda: stream.read(1048576), b''): digest.update(block) return digest.hexdigest() == expected except OSError: return False program = next((path for path in candidates if path.startswith('/') and installed(path)), None) if program is None: raise SystemExit('The installed Apex program was not found.') print(program) matches = [i for i, line in enumerate(lines) if line.startswith('Exec=')] if len(matches) != 1: note('The application menu entry is not available, so Apex was not added to the menu. Apex itself is installed: run ' + program) raise SystemExit(0) gtk = 'Adwaita:dark' if theme == 'dark' else 'Adwaita' def desktop_quote(value): value = value.replace('%', '%%') return '"' + ''.join(('\\' * 4 if character == '\\' else '\\' * 2 + character if character in '"$`' else character) for character in value) + '"' prefix = ('/usr/bin/env SDL_VIDEO_WAYLAND_PREFER_LIBDECOR=1 GTK_THEME=' + gtk + ' ') if theme else '/usr/bin/env ' if library: prefix += desktop_quote('LD_LIBRARY_PATH=' + library) + ' ' lines = [line for line in lines if not line.startswith('NoDisplay=')] index = [i for i, line in enumerate(lines) if line.startswith('Exec=')][0] lines[index] = 'Exec=' + prefix + desktop_quote(program) + ' %u' if theme: lines.insert(index + 1, 'NoDisplay=true') try: fd, temporary = tempfile.mkstemp(prefix='.apex-desktop-', dir=entry.parent) try: with os.fdopen(fd, 'w', encoding='utf-8') as file: file.write('\n'.join(lines) + '\n') file.flush() os.fsync(file.fileno()) os.chmod(temporary, 0o644) os.replace(temporary, entry) finally: if os.path.exists(temporary): os.unlink(temporary) except OSError: note('The application menu entry could not be updated. Apex itself is installed: run ' + program) PY IFS= read -r program < "$work/program" || true [[ "$program" == /* ]] || { fail 'Apex was installed, but its program file could not be found. Run this installer again.'; return 1; } command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$data_home/applications" >/dev/null 2>&1 || true ui_send path program "$program" if [[ -n "$fhs_program" ]]; then printf '#!/bin/sh\nexec "%s" "%s" "$@"\n' "$fhs_program" "$program" > "${program%/*}/apex-nixos" && chmod 755 "${program%/*}/apex-nixos" && printf '%s\n' "On NixOS, start Apex from a terminal with ${program%/*}/apex-nixos; the menu entry already does this." fi stage_done menu 'Added to your application menu' stage requirements 'Worker requirements' if grep -q -- '--check-requirements' "$work/help"; then local requirements_status=0 requirement_line='' ${apex_run[@]+"${apex_run[@]}"} "$work/apex" --check-requirements > "$work/requirements.txt" 2>&1 || requirements_status=$? cat "$work/requirements.txt" if (( requirements_status != 0 )); then while IFS= read -r requirement_line; do ui_send requirements line "$requirement_line"; done < "$work/requirements.txt" ui_send stage requirements failed 'System steps are needed before an instance can start' fail 'Apex was installed. Resolve the system steps above, then run apex --check-requirements again. Saved accounts and settings were kept. Exit status 3 means installed with system steps remaining.' || true return 3 fi stage_done requirements 'Host requirements passed; each instance also checks at launch' else [[ -z "$mode" ]] || printf ' %s\n' 'This release has no separate requirement check; it checks them when an instance starts.' stage_done requirements 'This release checks worker requirements when an instance starts' fi if ui_alive; then ui_send finish ok "$program" printf '\n%s\n' 'Apex is installed. Finish in the installer window.' ui_wait case "$ui_status" in 0) local -a launch=(env) [[ "$browser" != apex ]] || launch+=("LD_LIBRARY_PATH=$browser_home${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}") if command -v setsid >/dev/null 2>&1 && setsid -f "${launch[@]}" ${apex_run[@]+"${apex_run[@]}"} "$program" > /dev/null 2>&1 < /dev/null; then printf '%s\n' 'Apex is starting.' else printf '%s\n' "Apex could not be started from here. Open it from your application menu, or run $program" fi ;; 10) printf '%s\n' "Apex was not started because the Terms and Conditions were not accepted. Apex stays installed; open it from your application menu or run $program when you are ready." ;; *) printf '%s\n' 'Open Apex from your application menu.' ;; esac return 0 fi if [[ -n "$mode" ]]; then printf '\n %-13s %s\n' 'Program:' "$program" 'Data:' "$data_home/apex" 'Logs:' "$state_home/apex" [[ "$browser" != apex ]] || printf ' %-13s %s\n' 'WebKitGTK:' "$browser_home" printf ' %-13s %s\n' 'Terms:' 'https://apexclient.org/legal' fi if [[ -n "$service" ]]; then printf '\n%s\n' 'Apex is installed. Setting up CLI mode as a service that starts with this machine...' ${apex_run[@]+"${apex_run[@]}"} "$program" --cli setup < /dev/tty || { fail "CLI mode setup did not finish. Run $program --cli setup to try again."; return 1; } elif [[ -n "$theme" ]]; then printf '\n%s\n' 'Apex is installed in Linux.' elif [[ -n "${WSL_DISTRO_NAME:-}${WSL_INTEROP:-}" ]]; then printf '\n%s\n' "Apex is installed in Linux. Run $program to start it here." printf '%s\n' 'To add Apex to the Windows Start menu and Settings > Apps, run this in Windows PowerShell:' ' irm https://apexclient.org/wininstall.ps1 | iex' elif [[ -z "${DISPLAY:-}" && -z "${WAYLAND_DISPLAY:-}" ]]; then printf '\n%s\n' "Apex is installed. Run $program --cli to use it without a window, or $program --cli setup to run it as a service that starts with this machine." else printf '\n%s\n' 'Apex is installed. Open Apex from your application menu.'; fi ) apex_install "$@"