#!/bin/sh
# Agentura Local — Linux installer.
#
#   curl -fsSL https://agentura.ro/downloads/agenturalocal/install.sh | sh
#
# Everything is defined as functions and main() is called on the very last
# line. Piping a script into a shell executes bytes as they arrive, so a
# connection that drops mid-transfer would otherwise run half a command; this
# way a truncated download does nothing at all.
#
# POSIX sh on purpose — Mint has bash, but Debian/Ubuntu server images and
# some containers only have dash, and an installer is the worst place to
# discover a bashism.

set -eu

BASE_URL="${AGENTURA_BASE_URL:-https://agentura.ro/downloads/agenturalocal}"
VERSION="${AGENTURA_VERSION:-1.27.6}"
BIN_NAME="agentura-local"

# The published binaries are built on Debian 12, but the highest glibc symbol
# version they actually reference is 2.34 (verified with readelf, not assumed
# from the base image — the base is the ceiling, the symbols are the floor).
# Anything older fails at exec with "GLIBC_2.34 not found", which tells the
# user nothing, so check up front and name the distributions instead.
MIN_GLIBC_MINOR=34

RED=''; BOLD=''; DIM=''; OFF=''
if [ -t 1 ] && [ -t 2 ]; then
  RED=$(printf '\033[31m'); BOLD=$(printf '\033[1m')
  DIM=$(printf '\033[2m'); OFF=$(printf '\033[0m')
fi

say()  { printf '%s\n' "$*"; }
step() { printf '%s==>%s %s\n' "$BOLD" "$OFF" "$*"; }
warn() { printf '%s!%s  %s\n' "$RED" "$OFF" "$*" >&2; }
die()  { printf '%serror:%s %s\n' "$RED" "$OFF" "$*" >&2; exit 1; }

have() { command -v "$1" >/dev/null 2>&1; }

detect_platform() {
  [ "$(uname -s)" = "Linux" ] || die "This installer is for Linux. On macOS and Windows, download the app from your Agentura platform's Downloads page"
  case "$(uname -m)" in
    aarch64|arm64) ARCH=arm64 ;;
    x86_64|amd64)  ARCH=amd64 ;;
    *) die "Unsupported CPU architecture: $(uname -m). Agentura Local ships for arm64 and amd64." ;;
  esac
}

check_glibc() {
  # "ldd (Ubuntu GLIBC 2.39-0ubuntu8.2) 2.39" -> 2.39
  ver=$(ldd --version 2>/dev/null | awk 'NR==1 {print $NF}')
  case "$ver" in
    2.*) ;;
    *) warn "Could not determine the glibc version; continuing anyway."; return 0 ;;
  esac
  minor=${ver#2.}
  minor=${minor%%.*}
  case "$minor" in
    ''|*[!0-9]*) warn "Could not parse the glibc version ($ver); continuing anyway."; return 0 ;;
  esac
  if [ "$minor" -lt "$MIN_GLIBC_MINOR" ]; then
    die "This build needs glibc 2.$MIN_GLIBC_MINOR or newer, and this system has $ver.
       That means Ubuntu 20.04 or older, or a derivative of one (Linux Mint 20.x
       and earlier). Upgrade the distribution, or get in touch for a build
       against an older base: your Agentura platform's Downloads page"
  fi
}

# The app is a WebKitGTK window; without these it installs fine and then fails
# to open with a dynamic-linker error.
ensure_runtime_libs() {
  missing=''
  have_lib() {
    # ldconfig lives in /sbin and is not always on a plain user's PATH, so
    # fall back to looking in the multiarch library directories directly.
    if have ldconfig && ldconfig -p 2>/dev/null | grep -q "$1"; then return 0; fi
    for d in /usr/lib /usr/lib64 /usr/lib/*-linux-gnu* /lib/*-linux-gnu*; do
      [ -e "$d/$2" ] && return 0
    done
    return 1
  }
  have_lib 'libwebkit2gtk-4\.1\.so\.0' 'libwebkit2gtk-4.1.so.0' || missing="$missing libwebkit2gtk-4.1-0"
  have_lib 'libgtk-3\.so\.0'            'libgtk-3.so.0'          || missing="$missing libgtk-3-0"
  [ -n "$missing" ] || return 0

  if have apt-get; then
    step "Installing missing libraries:$missing"
    # shellcheck disable=SC2086
    if ! { $SUDO apt-get update -qq && $SUDO apt-get install -y $missing; }; then
      die "Could not install:$missing
       Run this yourself, then re-run the installer:
         sudo apt-get install -y$missing"
    fi
  else
    die "Missing runtime libraries:$missing
       This installer only knows how to install those with apt (Debian, Ubuntu, Mint).
       Install the GTK 3 and WebKitGTK 4.1 runtimes with your package manager, then re-run."
  fi
}

fetch() {
  # $1 url, $2 destination
  if have curl; then
    curl -fsSL --proto '=https' --tlsv1.2 -o "$2" "$1"
  elif have wget; then
    wget -q --https-only -O "$2" "$1"
  else
    die "Neither curl nor wget is installed."
  fi
}

verify_checksum() {
  # $1 file, $2 expected-name-in-SHA256SUMS
  expected=$(grep -E "[[:space:]]\*?$2\$" "$TMP/SHA256SUMS.txt" | awk '{print $1}' | head -1)
  [ -n "$expected" ] || die "No published checksum for $2 — refusing to install."
  if have sha256sum;  then actual=$(sha256sum "$1" | awk '{print $1}')
  elif have shasum;   then actual=$(shasum -a 256 "$1" | awk '{print $1}')
  else die "Neither sha256sum nor shasum is available; refusing an unverified installation."
  fi
  [ "$actual" = "$expected" ] || die "Checksum mismatch for $2.
       expected $expected
       got      $actual
       Refusing to install. Try again, and if it repeats, report it."
}

pick_install_dir() {
  if [ -n "$SUDO" ] || [ -w /usr/local/bin ]; then
    INSTALL_DIR=/usr/local/bin
  else
    INSTALL_DIR="$HOME/.local/bin"
    NEEDS_PATH_HINT=1
  fi
  INSTALL_DIR="${AGENTURA_INSTALL_DIR:-$INSTALL_DIR}"
}

install_desktop_entry() {
  # Always the invoking user's home, never root's: the launcher belongs to the
  # person who will click it, not to the sudo that copied the binary.
  home=$HOME
  [ -n "${SUDO_USER:-}" ] && home=$(getent passwd "$SUDO_USER" 2>/dev/null | cut -d: -f6) || true
  [ -n "$home" ] || return 0
  apps="$home/.local/share/applications"
  icons="$home/.local/share/icons/hicolor/512x512/apps"
  mkdir -p "$apps" "$icons" 2>/dev/null || return 0

  if fetch "$BASE_URL/agentura-local.png" "$TMP/icon.png" 2>/dev/null; then
    cp "$TMP/icon.png" "$icons/agentura-local.png" 2>/dev/null || true
  fi

  cat > "$apps/agentura-local.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=Agentura Local
Comment=Connect this computer to your Agentura agent
Exec=$INSTALL_DIR/$BIN_NAME
Icon=agentura-local
Terminal=false
Categories=Network;Utility;
StartupNotify=true
DESKTOP
  chmod 644 "$apps/agentura-local.desktop" 2>/dev/null || true
  if [ -n "${SUDO_USER:-}" ]; then
    chown -R "$SUDO_USER" "$apps/agentura-local.desktop" "$icons/agentura-local.png" 2>/dev/null || true
  fi
  have update-desktop-database && update-desktop-database "$apps" >/dev/null 2>&1 || true
}

main() {
  detect_platform

  SUDO=''
  if [ "$(id -u)" -ne 0 ] && have sudo; then SUDO='sudo'; fi
  NEEDS_PATH_HINT=0

  check_glibc
  ensure_runtime_libs

  TMP=$(mktemp -d)
  trap 'rm -rf "$TMP"' EXIT INT TERM

  asset="AgenturLocal-$VERSION-linux-$ARCH"
  rel="$BASE_URL/releases/$VERSION"

  step "Downloading Agentura Local $VERSION ($ARCH)"
  fetch "$rel/SHA256SUMS.txt" "$TMP/SHA256SUMS.txt" || die "Could not reach $rel — is the version right?"
  fetch "$rel/$asset" "$TMP/$asset" || die "Download failed: $rel/$asset"

  step "Verifying checksum"
  verify_checksum "$TMP/$asset" "$asset"

  pick_install_dir
  step "Installing to $INSTALL_DIR/$BIN_NAME"
  $SUDO mkdir -p "$INSTALL_DIR"
  chmod 755 "$TMP/$asset"
  # install(1) replaces the file atomically, so upgrading while the app is
  # running does not corrupt the copy the kernel has mapped.
  $SUDO install -m 755 "$TMP/$asset" "$INSTALL_DIR/$BIN_NAME"

  install_desktop_entry

  say ""
  say "${BOLD}Agentura Local $VERSION is installed.${OFF}"
  say ""
  say "  Start it from your applications menu, or run: ${BOLD}$BIN_NAME${OFF}"
  say "  Then paste the device token from your agent's page in the Agentura portal."
  say ""
  if [ "$NEEDS_PATH_HINT" = "1" ]; then
    case ":$PATH:" in
      *":$INSTALL_DIR:"*) ;;
      *) warn "$INSTALL_DIR is not on your PATH. Add it, or run $INSTALL_DIR/$BIN_NAME directly." ;;
    esac
  fi
  say "${DIM}Desktop control on Linux requires an X11 session. Wayland is not supported.${OFF}"
  say "${DIM}To upgrade later, run this installer again.${OFF}"
}

main "$@"
