#!/usr/bin/env bash
# Installs or updates GOAT on Linux, with no root password:
#   curl -fsSL https://qoleton.dev/chat/install.sh | bash
# Run it again any time to update. GOAT doesn't update itself on Linux.
set -euo pipefail

BASE='https://qoleton.dev/chat/linux'
DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
DIR="$DATA/goat"
APP="$DIR/app"
BIN="$HOME/.local/bin/goat"
DESKTOP="$DATA/applications/goat.desktop"

say() { printf '  %s\n' "$*"; }
fail() { printf '\n  \033[31m%s\033[0m\n\n' "$*" >&2; exit 1; }

printf '\n  \033[36mSetting up GOAT\033[0m\n\n'

for tool in curl tar sha256sum; do
    command -v "$tool" >/dev/null || fail "$tool is needed. Install it with your package manager and run this again."
done
[ "$(uname -m)" = x86_64 ] || fail "GOAT doesn't have a Linux build for $(uname -m) yet."

latest="$(curl -fsSL "$BASE/latest")" || fail "Couldn't reach qoleton.dev to find the latest GOAT version."
read -r version sha256 <<<"$latest"
[ -n "${version:-}" ] && [ -n "${sha256:-}" ] || fail "Couldn't read the latest GOAT version."

mkdir -p "$DIR" "$(dirname "$BIN")" "$(dirname "$DESKTOP")"

if [ -x "$APP/goat-desktop" ] && [ "$(cat "$DIR/version" 2>/dev/null)" = "$version" ]; then
    say "GOAT $version is already installed."
else
    say "Downloading GOAT $version (about 120 MB)..."
    tmp="$(mktemp -d "$DIR/download.XXXXXX")"
    trap 'rm -rf "$tmp"' EXIT
    # The checksum in the address keeps a CDN from serving an older copy of this file.
    curl -fL --progress-bar -o "$tmp/goat.tar.gz" "$BASE/GOAT-$version-linux-x64.tar.gz?sha=$sha256" \
        || fail "The download failed. Run this again to retry."
    printf '%s  %s\n' "$sha256" "$tmp/goat.tar.gz" | sha256sum -c --status \
        || fail "The download was damaged, so nothing was installed. Run this again to retry."

    say "Installing..."
    mkdir "$tmp/app"
    tar -xzf "$tmp/goat.tar.gz" -C "$tmp/app" --strip-components=1
    [ -x "$tmp/app/goat-desktop" ] || fail "The download didn't contain GOAT, so nothing was installed."
    # Swap at the end, so a failed update leaves the old copy working.
    rm -rf "$APP"
    mv "$tmp/app" "$APP"
    printf '%s\n' "$version" >"$DIR/version"
fi

ln -sf "$APP/goat-desktop" "$BIN"

cat >"$DESKTOP" <<EOF
[Desktop Entry]
Type=Application
Name=GOAT
Comment=Chat, voice and screen sharing
Exec="$APP/goat-desktop" %u
Terminal=false
Categories=Network;InstantMessaging;Chat;
MimeType=x-scheme-handler/goat;
EOF
command -v update-desktop-database >/dev/null && update-desktop-database "$(dirname "$DESKTOP")" 2>/dev/null || true
command -v xdg-mime >/dev/null && xdg-mime default goat.desktop x-scheme-handler/goat 2>/dev/null || true

# Chromium's sandbox needs unprivileged user namespaces, or a helper that root has set up.
# Ubuntu 23.10+ and some other distros restrict the former.
sandbox_ok=true
if [ "$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null)" = 1 ] \
    || [ "$(cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null)" = 0 ] \
    || ! unshare -Ur true 2>/dev/null; then
    helper="$APP/chrome-sandbox"
    if [ "$(stat -c '%u:%a' "$helper" 2>/dev/null)" != 0:4755 ]; then
        sandbox_ok=false
    fi
fi

printf '\n  \033[32mDone!\033[0m GOAT is in your app menu. Run this command again to update it.\n\n'

if [ "$sandbox_ok" = false ]; then
    say "One more step: your system needs this once after each install or update."
    say "It lets GOAT run in its security sandbox, and asks for your password:"
    printf '\n    sudo chown root:root "%s" && sudo chmod 4755 "%s"\n\n' "$helper" "$helper"
    say "Then open GOAT from your app menu."
    printf '\n'
elif pgrep -x goat-desktop >/dev/null; then
    say "GOAT is already open. Quit and reopen it to use this version."
elif [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
    nohup "$APP/goat-desktop" >/dev/null 2>&1 &
fi
