#!/bin/sh
# Kindredly Companion for Linux — install, update or remove it for everyone on this computer.
# Tested on Ubuntu, Linux Mint and Zorin OS (HAT-198, HAT-602); elsewhere it installs, and says so first.
#
#   wget -nv -O- https://thetaset.s3.us-west-2.amazonaws.com/artifacts_production/companion/linux/latest/kindredly_companion_linux_install_latest.sh | sudo sh
#   sudo /usr/lib/kindredly-companion/install.sh --update       (the update timer runs this)
#   sudo /usr/lib/kindredly-companion/install.sh --uninstall
#
# Needs root on purpose (HAT-173). The Companion protects a child, so the child's own account —
# which must not have sudo — can neither delete it nor stop it: the app is root-owned under /opt,
# and a root service (kindredly-companion-guard) starts it in every desktop session and brings it
# back after a kill while the Companion says this computer is supervised.
#
# Root is also what lets Chromium's sandbox run. Ubuntu 24.04 and later block the unprivileged user
# namespaces it normally uses; its fallback helper must be root-owned and setuid, which nothing a
# user installs can be. A per-user AppImage therefore aborted at start on those systems (HAT-172).
#
# wget, not curl, in the command a parent pastes: Ubuntu Desktop installs wget and not curl.

set -eu

# One block, so the shell reads all of it before running any of it: a download cut off halfway runs
# nothing, and no command started here can read the rest of the script from the pipe.
{

FEED="https://thetaset.s3.us-west-2.amazonaws.com/artifacts_production/companion/linux/latest"
PREFIX=/opt/kindredly-companion
LIB=/usr/lib/kindredly-companion
UNITS=/etc/systemd/system
POLICY=/usr/share/polkit-1/actions/ai.kindredly.companion.policy
INSTALLER_URL="$FEED/kindredly_companion_linux_install_latest.sh"

MODE=install
case "${1:-}" in
  --update) MODE=update ;;
  --uninstall) MODE=uninstall ;;
  "") ;;
  *) echo "Usage: install.sh [--update | --uninstall]" >&2; exit 2 ;;
esac

say() { [ "$MODE" = update ] || echo "$*"; }

if [ "$(id -u)" != 0 ]; then
  echo "Kindredly Companion is installed for everyone on this computer, so it needs administrator rights." >&2
  echo "Run it with sudo:" >&2
  echo "  wget -nv -O- $INSTALLER_URL | sudo sh" >&2
  exit 1
fi

# Tested on Ubuntu and the desktops built on it that families use (HAT-198, HAT-602). Anywhere else
# it still installs, and says so before it starts.
if [ "$MODE" = install ]; then
  distro_id=""; distro_name=""
  if [ -r /etc/os-release ]; then
    distro_id="$(. /etc/os-release; echo "${ID:-}")"
    distro_name="$(. /etc/os-release; echo "${PRETTY_NAME:-}")"
  fi
  case "$distro_id" in
    ubuntu | linuxmint | zorin) ;;
    *)
      echo "Kindredly Companion has been tested on Ubuntu, Linux Mint and Zorin OS."
      echo "${distro_name:-This system} has not been tested, so parts of it may not work."
      echo "" ;;
  esac

  # The guard starts the Companion through the person's own systemd manager (`systemctl --user -M
  # user@`), which systemd 248 added. Older (Ubuntu 20.04, Linux Mint 20) would install a Companion
  # that never starts by itself, so say so instead.
  systemd_version="$(systemctl --version 2>/dev/null | awk 'NR == 1 { print $2 + 0 }')"
  if [ -n "$systemd_version" ] && [ "$systemd_version" -gt 0 ] && [ "$systemd_version" -lt 248 ]; then
    echo "Kindredly Companion needs a newer system: Ubuntu 22.04, Linux Mint 21, Zorin OS 17 or later." >&2
    echo "${distro_name:-This system} is too old, so nothing was installed." >&2
    exit 1
  fi
fi

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else echo "Kindredly Companion needs curl or wget to download." >&2; exit 1
  fi
}

# Every person's home folder on this computer, for the per-user leftovers of the old install.
homes() { getent passwd | awk -F: '$3 >= 1000 && $3 < 65534 { print $6 }'; }

remove_old_per_user_install() {
  for home in $(homes); do
    [ -d "$home" ] || continue
    unit="$home/.config/systemd/user/kindredly-companion.service"
    [ -e "$unit" ] || [ -e "$home/.local/lib/kindredly-companion" ] || [ -e "$home/.config/autostart/kindredly-companion.desktop" ] || continue
    rm -rf "$home/.local/lib/kindredly-companion"
    rm -f "$home/.local/bin/kindredly-companion" \
      "$home/.local/share/applications/kindredly-companion.desktop" \
      "$home/.config/autostart/kindredly-companion.desktop" \
      "$unit"
  done
}

# SIGTERM first, so each Companion closes itself and records that it did. One still running after a
# few seconds is killed (CMP-50): older builds answered SIGTERM on a supervised computer with their
# quit window and carried on, running from the files this update is about to delete.
companions_running() {
  pgrep -f "^$PREFIX/kindredly-electron" >/dev/null 2>&1 || pgrep -f '/tmp/\.mount_kindre[^ ]*/kindredly-electron' >/dev/null 2>&1
}
stop_running_companions() {
  # Says this SIGTERM is the installer's, so the next start does not report the exit to the parent as
  # the Companion being closed (CMP-49). Root's file in root's folder: a child's account cannot make it.
  mkdir -p /run/kindredly-companion 2>/dev/null && : > /run/kindredly-companion/updating 2>/dev/null || true
  pkill -f "^$PREFIX/kindredly-electron" 2>/dev/null || true
  pkill -f '/tmp/\.mount_kindre[^ ]*/kindredly-electron' 2>/dev/null || true
  waited=0
  while [ "$waited" -lt 5 ] && companions_running; do
    sleep 1
    waited=$((waited + 1))
  done
  if companions_running; then
    pkill -KILL -f "^$PREFIX/kindredly-electron" 2>/dev/null || true
    pkill -KILL -f '/tmp/\.mount_kindre[^ ]*/kindredly-electron' 2>/dev/null || true
  fi
  # The marker stays until this script ends (the EXIT trap): the guard starts nothing and writes no
  # restart down while it is there, and the old guard is still running until the new one replaces it.
}

if [ "$MODE" = uninstall ]; then
  systemctl disable --now kindredly-companion-guard.service kindredly-companion-update.timer 2>/dev/null || true
  rm -f "$UNITS/kindredly-companion-guard.service" "$UNITS/kindredly-companion-update.service" "$UNITS/kindredly-companion-update.timer"
  systemctl daemon-reload 2>/dev/null || true
  stop_running_companions
  if [ -e /etc/apparmor.d/kindredly-companion ]; then
    apparmor_parser -R /etc/apparmor.d/kindredly-companion 2>/dev/null || true
    rm -f /etc/apparmor.d/kindredly-companion
  fi
  # The guard's records and event logs go too (CMP-48): nothing is left to restart.
  rm -rf "$PREFIX" "$LIB" /run/kindredly-companion /var/lib/kindredly-companion
  rm -f /usr/bin/kindredly-companion /usr/share/applications/kindredly-companion.desktop /usr/share/pixmaps/kindredly-companion.png "$POLICY"
  remove_old_per_user_install
  echo "Kindredly Companion was removed from this computer."
  exit 0
fi

case "$(uname -m)" in
  x86_64|amd64) ;;
  *) echo "Kindredly Companion for Linux runs on 64-bit Intel and AMD computers only (this one is $(uname -m))." >&2; exit 1 ;;
esac

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"; rm -f /run/kindredly-companion/updating' EXIT

# What the feed serves: its version, file and checksum, from the same file the app's updater reads.
fetch "$FEED/latest-linux.yml" "$WORK/latest.yml"
VERSION="$(sed -n 's/^version:[[:space:]]*//p' "$WORK/latest.yml" | head -n 1)"
FILE="$(sed -n 's/^[[:space:]]*-[[:space:]]*url:[[:space:]]*//p' "$WORK/latest.yml" | head -n 1)"
SHA512_B64="$(sed -n 's/^[[:space:]]*sha512:[[:space:]]*//p' "$WORK/latest.yml" | head -n 1)"
[ -n "$VERSION" ] && [ -n "$FILE" ] && [ -n "$SHA512_B64" ] || { echo "The download feed did not say which version to install." >&2; exit 1; }

if [ "$MODE" = update ] && [ "$(cat "$PREFIX/VERSION" 2>/dev/null)" = "$VERSION" ]; then
  exit 0
fi

say "Downloading Kindredly Companion $VERSION…"
fetch "$FEED/$FILE" "$WORK/companion.AppImage"
expected="$(printf '%s' "$SHA512_B64" | base64 -d | od -An -v -tx1 | tr -d ' \n')"
actual="$(sha512sum "$WORK/companion.AppImage" | cut -d' ' -f1)"
if [ "$expected" != "$actual" ]; then
  echo "The download did not match the feed's checksum, so nothing was installed." >&2
  exit 1
fi

# Unpack. The AppImage unpacks itself, which needs no FUSE.
chmod +x "$WORK/companion.AppImage"
(cd "$WORK" && ./companion.AppImage --appimage-extract >/dev/null)
NEW="$PREFIX.new"
rm -rf "$NEW"
mv "$WORK/squashfs-root" "$NEW"
chown -R root:root "$NEW"
chmod -R u+rwX,go+rX,go-w "$NEW"
# Chromium's sandbox helper: root-owned and setuid, as Chrome's own package installs it.
chmod 4755 "$NEW/chrome-sandbox"
echo "$VERSION" > "$NEW/VERSION"

stop_running_companions
rm -rf "$PREFIX.old"
[ -d "$PREFIX" ] && mv "$PREFIX" "$PREFIX.old"
mv "$NEW" "$PREFIX"
rm -rf "$PREFIX.old"

# Ubuntu 24.04+: let the sandbox use user namespaces, as Ubuntu's own profiles for Chrome do.
if [ -d /etc/apparmor.d ] && command -v apparmor_parser >/dev/null 2>&1; then
  cat > /etc/apparmor.d/kindredly-companion <<'PROFILE'
abi <abi/4.0>,
include <tunables/global>

profile kindredly-companion /opt/kindredly-companion/kindredly-electron flags=(unconfined) {
  userns,
  include if exists <local/kindredly-companion>
}
PROFILE
  apparmor_parser -r /etc/apparmor.d/kindredly-companion 2>/dev/null || rm -f /etc/apparmor.d/kindredly-companion
fi

ln -sf "$PREFIX/kindredly-electron" /usr/bin/kindredly-companion
if [ -f "$PREFIX/kindredly-electron.png" ]; then
  install -m 644 "$PREFIX/kindredly-electron.png" /usr/share/pixmaps/kindredly-companion.png
fi
cat > /usr/share/applications/kindredly-companion.desktop <<'DESKTOP'
[Desktop Entry]
Type=Application
Name=Kindredly Companion
Comment=Kindredly's protections on this computer
Exec=/usr/bin/kindredly-companion %U
Icon=kindredly-companion
StartupWMClass=Kindredly Companion
Terminal=false
Categories=Utility;
DESKTOP
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database -q /usr/share/applications || true

mkdir -p "$LIB"
install -m 755 "$PREFIX/resources/linux/kindredly-companion-guard.sh" "$LIB/guard.sh"
# What polkit says when a guardian turns close protection off or unlinks a supervised account: the
# Companion then runs `guard.sh --release` through pkexec, which takes an administrator's password,
# because nothing in the child's own folder can tell the guard a guardian asked (CMP-48).
if [ -d "${POLICY%/*}" ]; then
  cat > "$POLICY" <<POLICYFILE
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
  "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <vendor>Kindredly</vendor>
  <action id="ai.kindredly.companion.release">
    <description>Let Kindredly Companion stay closed</description>
    <message>Authentication is required to let Kindredly Companion stay closed for this account.</message>
    <defaults>
      <allow_any>no</allow_any>
      <allow_inactive>no</allow_inactive>
      <allow_active>auth_admin</allow_active>
    </defaults>
    <annotate key="org.freedesktop.policykit.exec.path">$LIB/guard.sh</annotate>
  </action>
</policyconfig>
POLICYFILE
  chmod 644 "$POLICY"
fi
# Keep a copy of this installer for the update timer. Fetched rather than copied: run as
# `wget … | sudo sh`, this script has no file of its own.
if fetch "$INSTALLER_URL" "$WORK/install.sh" 2>/dev/null; then install -m 755 "$WORK/install.sh" "$LIB/install.sh"; fi

if ! command -v systemctl >/dev/null 2>&1 || [ ! -d /run/systemd/system ]; then
  remove_old_per_user_install
  say ""
  say "Kindredly Companion $VERSION is installed, but this computer does not use systemd, so nothing"
  say "will start it at sign-in or bring it back if it is closed. Open it from your app menu."
  exit 0
fi

cat > "$UNITS/kindredly-companion-guard.service" <<UNIT
[Unit]
Description=Kindredly Companion guard (keeps the Companion running in each desktop session)
After=systemd-logind.service

[Service]
ExecStart=$LIB/guard.sh
Restart=always
RestartSec=5
# Stopping or restarting the guard must not take every Companion with it: they are its children,
# and systemd's default stops the whole group. An update stops them itself, on purpose.
KillMode=process

[Install]
WantedBy=multi-user.target
UNIT
cat > "$UNITS/kindredly-companion-update.service" <<UNIT
[Unit]
Description=Update Kindredly Companion
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=$LIB/install.sh --update
UNIT
cat > "$UNITS/kindredly-companion-update.timer" <<UNIT
[Unit]
Description=Check for a new Kindredly Companion

[Timer]
OnBootSec=10min
OnUnitActiveSec=6h
RandomizedDelaySec=30min

[Install]
WantedBy=timers.target
UNIT

remove_old_per_user_install
# An update restarts every session's Companion, not only supervised ones: forget which sessions
# the guard has already started, so it starts each again as it would at login.
rm -f /run/kindredly-companion/session-* 2>/dev/null || true

systemctl daemon-reload
systemctl enable kindredly-companion-update.timer >/dev/null 2>&1
systemctl start kindredly-companion-update.timer >/dev/null 2>&1 || true
systemctl enable kindredly-companion-guard.service >/dev/null 2>&1
systemctl restart kindredly-companion-guard.service

# The top bar icon needs nothing from here: the Companion asks GNOME to load the AppIndicator
# extension live, in each person's own session, the first time it starts (linuxTray.ts). Installing
# Ubuntu's package here only took effect at the next sign-in, and then ran beside that one.

# A desktop install has the libraries Chromium needs; a server or a bare install does not, and there
# the Companion cannot start at all (HAT-200: an Ubuntu 24.04 server image lacked GTK and 12 more).
# Say so, rather than that it starts at every sign-in.
missing="$(ldd "$PREFIX/kindredly-electron" 2>/dev/null | awk '/not found/ { print $1 }' | tr '\n' ' ')"

say ""
say "Kindredly Companion $VERSION is installed for everyone on this computer."
if [ -n "$missing" ]; then
  say "It cannot start here: this computer has no desktop. It runs on Ubuntu Desktop."
  say "Missing: $missing"
else
  say "It starts in each desktop session within a few seconds, and from now on at every sign-in."
fi
say "To remove it: sudo $LIB/install.sh --uninstall"

# An administrator can use sudo, and sudo removes the Companion, so a child's account must not be
# one (HAT-198). Named here because this is when the parent is at the computer to change it.
admins="$(getent group sudo admin wheel 2>/dev/null | cut -d: -f4 | tr ',' '\n' | sed '/^$/d' | sort -u | tr '\n' ' ')"
if [ -n "$admins" ]; then
  say ""
  say "Administrator accounts here: $admins"
  say "Anyone using one of these can remove the Companion. If a child uses one, make it a"
  # Where each desktop keeps it: Cinnamon's own settings on Linux Mint, GNOME's elsewhere.
  if [ "${distro_id:-}" = linuxmint ]; then
    say "Standard account in System Settings → Users and Groups."
  else
    say "Standard account: turn off Administrator in Settings → System → Users."
  fi
fi
}
