#!/bin/bash
set -euo pipefail
export LC_ALL=C DEBIAN_FRONTEND=noninteractive
umask 022

INSTALL=/opt/OpenBot
RELEASES=https://github.com/nightly-labs/openbot/releases
LOCK=/run/openbot-update.lock
SCRATCH=/var/tmp
RESTORE=/var/lib/ascii-lazy
HOSTED_FILES=(openbot-hosted-server openbot-hosted-env openbot-hosted-update openbot-hosted-keyring openbot)
REQUESTS=/run/openbot
STATE=/run/openbot-update.state
UNIT_DIRECTORY=/etc/systemd/system
REQUEST_UNITS=(openbot-update-request.path openbot-update-request.service)
UNITS=(openbot.service openbot-update.service openbot-update.timer openbot-update-apply.service "${REQUEST_UNITS[@]}")
BOAT_USER=user
BOAT_PRE_STOP=/home/$BOAT_USER/.boat/pre-stop
BOAT_IGNORE=/home/$BOAT_USER/.boatignore
START_LOOP_STATUS=78
SAFE_MODE_MARKER=$REQUESTS/server-safe-mode
STAGE_STAMP=/run/openbot-update.staged
STAGE_INTERVAL_MINUTES=360
RELEASE_FILES=(packages.txt optional-packages.txt openbot-hosted.apparmor openbot-boat-pre-stop "${HOSTED_FILES[@]}" "${UNITS[@]}")

fail() {
  echo "$*" >&2
  exit 1
}

fetch() {
  curl --fail --location --proto '=https' --proto-redir '=https' --tlsv1.2 --silent --show-error --retry 3 "$@"
}

version_of() {
  local entry
  for entry in "$1"/*.desktop; do
    if [ -f "$entry" ]; then
      sed -n 's/^X-AppImage-Version=//p' "$entry" | head -n 1
      return 0
    fi
  done
  return 0
}

restoring() {
  [ -e "$RESTORE/active" ] && [ ! -e "$RESTORE/hydration-done" ]
}

wait_for_restore() {
  local second
  for ((second = 0; second < 240; second++)); do
    restoring || return 0
    sleep 1
  done
  fail "The disk of the server is still being restored."
}

staged_version() {
  local ready
  [ -f "$INSTALL/staged.ready" ] || return 0
  ready=$(<"$INSTALL/staged.ready")
  if [ -n "$ready" ] && [ "$(version_of "$INSTALL/staged")" = "$ready" ]; then echo "$ready"; fi
  return 0
}

newer() {
  [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | tail -n 1)" = "$1" ]
}

installed_package() {
  dpkg-query -W -f='${db:Status-Status}' "$1" 2>/dev/null | grep -qx installed
}

available_package() {
  local candidate
  candidate=$(apt-cache policy "$1" 2>/dev/null | sed -n 's/^ *Candidate: *//p')
  [ -n "$candidate" ] && [ "$candidate" != "(none)" ]
}

apt_install() {
  apt-get -o DPkg::Lock::Timeout=600 install -y --no-install-recommends --no-remove "$@"
}

install_packages() {
  local optional=${2:-} package missing=() available=()
  while read -r package; do
    [[ -z $package || $package == \#* ]] && continue
    [[ $package =~ ^[a-z0-9][a-z0-9.+-]+$ ]] || fail "The package name is not valid: $package"
    [ -n "$optional" ] && command -v "$package" >/dev/null && continue
    installed_package "$package" || installed_package "${package%t64}" || missing+=("$package")
  done <"$1"
  [ "${#missing[@]}" -eq 0 ] && return 0
  dpkg --configure -a
  apt-get -o DPkg::Lock::Timeout=600 -o Acquire::AllowReleaseInfoChange::Label=true update
  for package in "${missing[@]}"; do
    if available_package "$package"; then
      available+=("$package")
    elif available_package "${package%t64}"; then
      available+=("${package%t64}")
    else
      echo "This system has no package $package. OpenBot continues without it." >&2
    fi
  done
  [ "${#available[@]}" -eq 0 ] && return 0
  if [ -z "$optional" ]; then
    apt_install "${available[@]}"
  else
    for package in "${available[@]}"; do
      if apt_install --simulate "$package" >/dev/null 2>&1; then
        apt_install "$package"
      else
        echo "This system cannot install $package without removing other packages. OpenBot continues without it." >&2
      fi
    done
  fi
  apt-get clean
}

install_optional_packages() {
  install_packages "$1" optional
}

unpack() {
  chmod 0700 "$1"
  (cd "$(dirname "$1")" && "./$(basename "$1")" --appimage-extract >/dev/null)
}

prepare_release() {
  [ -x "$1/openbot" ] || fail "The AppImage has no openbot executable."
  chown -R root:root "$1"
  chmod -R u+rwX,go=rX "$1"
  chmod 4755 "$1/chrome-sandbox"
}

copy_release() {
  rm -rf "$2"
  cp -a --no-preserve=ownership "$1" "$2"
}

repair_release_modes() {
  [ -d "$INSTALL/app" ] || return 0
  find "$INSTALL/app" ! -type l \( ! -perm -o=r -o \( -type d ! -perm -o=x \) \) \
    -printf 'Repaired the mode of %p.\n' -exec chmod u+rwX,go=rX {} +
}

swap_in() {
  : >"$INSTALL/.applying"
  copy_release "$INSTALL/staged" "$INSTALL/app"
}

finish_swap() {
  rm -f "$INSTALL/.applying"
  rm -rf "$INSTALL/staged" "$INSTALL/staged.ready"
}

stage_release() {
  rm -f "$INSTALL/staged.ready"
  copy_release "$1" "$INSTALL/staged"
  version_of "$INSTALL/staged" >"$INSTALL/staged.ready"
}

recover() {
  rm -rf "$SCRATCH"/openbot-update.*
}

start_loop_stopped() {
  [ "$(systemctl show --property=ActiveState --value openbot.service 2>/dev/null)" = failed ] || return 1
  [ "$(systemctl show --property=ExecMainStatus --value openbot.service 2>/dev/null)" = "$START_LOOP_STATUS" ]
}

safe_mode_running() {
  [ "$(systemctl show --property=ActiveState --value openbot.service 2>/dev/null)" = active ] || return 1
  [ -e "$SAFE_MODE_MARKER" ] || [ -L "$SAFE_MODE_MARKER" ]
}

stage_due() {
  [ -z "$(find "$STAGE_STAMP" -mmin "-$STAGE_INTERVAL_MINUTES" 2>/dev/null)" ]
}

check() {
  local staged=0 stopped=0 safe_mode=0
  if [ -x "$INSTALL/hosted/openbot-hosted-keyring" ]; then
    "$INSTALL/hosted/openbot-hosted-keyring" backup || echo "The copy of the keyring is not refreshed." >&2
  fi
  if start_loop_stopped || safe_mode_running; then stopped=1; fi
  if [ "$stopped" -eq 1 ] || stage_due; then
    set +e
    (
      set -e
      stage
    )
    staged=$?
    set -e
    if [ "$staged" -eq 0 ]; then touch "$STAGE_STAMP"; fi
  fi
  if safe_mode_running; then
    echo "OpenBot runs its safe mode. Stopping it."
    systemctl stop openbot.service || return 1
    safe_mode=1
  fi
  if [ "$safe_mode" -eq 1 ] || start_loop_stopped; then
    if [ -n "$(staged_version)" ]; then
      echo "OpenBot stopped its start loop. Installing the staged release and starting OpenBot."
      apply
    else
      echo "OpenBot stopped its start loop. Starting OpenBot again."
    fi
    systemctl start --no-block openbot.service
  fi
  return "$staged"
}

set_state() {
  printf '%s\n' "$*" >"$STATE.new"
  mv -f "$STATE.new" "$STATE"
}

download() {
  local pid bytes percent
  fetch --output "$2" "$1" &
  pid=$!
  while kill -0 "$pid" 2>/dev/null; do
    bytes=$(stat -c %s "$2" 2>/dev/null || echo 0)
    percent=0
    if [[ $3 =~ ^[1-9][0-9]{0,11}$ && $bytes =~ ^[0-9]+$ ]]; then percent=$((bytes * 100 / $3)); fi
    set_state downloading "$((percent > 100 ? 100 : percent))"
    sleep 1
  done
  wait "$pid"
}

allow_sandbox_capabilities() {
  local profile=/etc/apparmor.d/bwrap-userns-restrict
  local override=/etc/apparmor.d/local/bwrap-userns-restrict
  local rule='priority=1 allow pix /** -> &bwrap,'
  grep -qsF 'include if exists <local/bwrap-userns-restrict>' "$profile" || return 0
  grep -qsxF "$rule" "$override" && return 0
  mkdir -p /etc/apparmor.d/local
  printf '# OpenBot: the Claude sandbox needs capabilities in the programs that bwrap starts.\n%s\n' \
    "$rule" >>"$override"
  apparmor_parser --replace "$profile" && return 0
  sed -i -e '/^# OpenBot: /d' -e '/^priority=1 allow pix \/\*\* -> &bwrap,$/d' "$override"
  apparmor_parser --replace "$profile" 2>/dev/null || true
  echo "The AppArmor rule for the Claude sandbox is not installed." >&2
}

apparmor_predates_abi_4() {
  [ ! -e /etc/apparmor.d/abi/4.0 ] && command -v apparmor_parser >/dev/null &&
    ! apparmor_parser --skip-kernel-load --skip-cache "$1" >/dev/null 2>&1
}

install_hosted_file() {
  local source=$1 file=$2
  install -m 0755 "$source/$file" "$INSTALL/hosted/.$file.new"
  mv -f "$INSTALL/hosted/.$file.new" "$INSTALL/hosted/$file"
}

install_hosting() {
  local source=$1 user file unit changed=0
  user=$(<"$INSTALL/hosted/service-user")
  [[ $user =~ ^[a-zA-Z_][a-zA-Z0-9_-]*$ ]] || fail "The service user is not valid."
  for file in "${HOSTED_FILES[@]}"; do
    install_hosted_file "$source" "$file"
  done
  if apparmor_predates_abi_4 "$source/openbot-hosted.apparmor"; then
    rm -f /etc/apparmor.d/openbot-hosted
  else
    install -m 0644 "$source/openbot-hosted.apparmor" /etc/apparmor.d/openbot-hosted
  fi
  if command -v apparmor_parser >/dev/null && [ -d /sys/kernel/security/apparmor ]; then
    if [ -e /etc/apparmor.d/openbot-hosted ]; then
      apparmor_parser --replace /etc/apparmor.d/openbot-hosted ||
        echo "The AppArmor profile is not loaded." >&2
    fi
    allow_sandbox_capabilities
  fi
  for unit in "${UNITS[@]}"; do
    sed "s/@SERVICE_USER@/$user/g" "$source/$unit" >"$INSTALL/hosted/.unit.new"
    if ! cmp -s "$INSTALL/hosted/.unit.new" "$UNIT_DIRECTORY/$unit"; then
      install -m 0644 "$INSTALL/hosted/.unit.new" "$UNIT_DIRECTORY/$unit"
      changed=1
    fi
  done
  rm -f "$INSTALL/hosted/.unit.new"
  if [ "$changed" -eq 1 ]; then systemctl daemon-reload; fi
  systemctl enable --quiet openbot.service openbot-update-apply.service openbot-update.timer \
    openbot-update-request.path
  if self_hosted; then
    ln -sfn "$INSTALL/hosted/openbot" /usr/local/bin/openbot
  fi
  install_pre_stop "$source" || echo "The boat pre-stop hook is not installed." >&2
  install_boat_ignore || echo "The boat ignore file is not installed." >&2
  remove_lazy_harnesses || echo "The install-on-first-run agent commands of boat are not removed." >&2
}

self_hosted() {
  [ -r "$INSTALL/hosted/mode" ] && [ "$(<"$INSTALL/hosted/mode")" = self ]
}

install_pre_stop() {
  local source=$1/openbot-boat-pre-stop
  if self_hosted || [ ! -f "$source" ] || ! id "$BOAT_USER" >/dev/null 2>&1; then return 0; fi
  if [ -L "$BOAT_PRE_STOP" ] || { [ -e "$BOAT_PRE_STOP" ] && [ ! -f "$BOAT_PRE_STOP" ]; } ||
    { [ -f "$BOAT_PRE_STOP" ] && ! runuser -u "$BOAT_USER" -- grep -q '^# openbot-boat-pre-stop:' "$BOAT_PRE_STOP"; }; then
    echo "$BOAT_PRE_STOP is not from OpenBot. It stays, and OpenBot is not stopped before a disk save." >&2
    return 0
  fi
  runuser -u "$BOAT_USER" -- cmp -s "$source" "$BOAT_PRE_STOP" 2>/dev/null && return 0
  runuser -u "$BOAT_USER" -- install -D -m 0755 "$source" "${BOAT_PRE_STOP%/*}/.pre-stop.new"
  runuser -u "$BOAT_USER" -- mv -f "${BOAT_PRE_STOP%/*}/.pre-stop.new" "$BOAT_PRE_STOP"
}

install_boat_ignore() {
  local marker='# openbot-boatignore: installed by openbot-hosted-update. Changes to this file are replaced.'
  local content
  if self_hosted || ! id "$BOAT_USER" >/dev/null 2>&1; then return 0; fi
  content=$(printf '%s\n' "$marker" '/.npm/_cacache/')
  if [ -L "$BOAT_IGNORE" ] || { [ -e "$BOAT_IGNORE" ] && [ ! -f "$BOAT_IGNORE" ]; } ||
    { [ -f "$BOAT_IGNORE" ] && ! runuser -u "$BOAT_USER" -- grep -qxF "$marker" "$BOAT_IGNORE"; }; then
    echo "$BOAT_IGNORE is not from OpenBot. It stays." >&2
    return 0
  fi
  [ -f "$BOAT_IGNORE" ] && [ "$(runuser -u "$BOAT_USER" -- cat "$BOAT_IGNORE")" = "$content" ] && return 0
  printf '%s\n' "$content" | runuser -u "$BOAT_USER" -- tee "${BOAT_IGNORE%/*}/.boatignore.new" >/dev/null
  runuser -u "$BOAT_USER" -- mv -f "${BOAT_IGNORE%/*}/.boatignore.new" "$BOAT_IGNORE"
}

remove_lazy_harnesses() {
  local harnesses=/usr/local/lib/ascii-harnesses/bin launcher name
  if self_hosted || [ ! -d "$harnesses" ]; then return 0; fi
  for launcher in "$harnesses"/*; do
    [ -f "$launcher" ] && [ ! -L "$launcher" ] || continue
    case $(sed -n '2{p;q;}' "$launcher") in "# ascii-lazy-harness "*) ;; *) continue ;; esac
    name=${launcher##*/}
    if [ "$(sed -n '2{p;q;}' "/usr/local/bin/$name" 2>/dev/null)" = "# ascii-harness-shim" ]; then
      rm -f "/usr/local/bin/$name"
    fi
    rm -f "$launcher"
  done
}

stage() {
  local architecture manifest version path sha512 size current
  case $(uname -m) in
    x86_64) architecture=x86_64 manifest=latest-linux.yml ;;
    aarch64) architecture=arm64 manifest=latest-linux-arm64.yml ;;
    *) fail "OpenBot has no release for this machine." ;;
  esac
  if [ -e "$INSTALL/.applying" ]; then
    echo "The last update is not complete. It completes at the next start of the server." >&2
    return 0
  fi
  [ -x "$INSTALL/app/openbot" ] || fail "OpenBot is not installed."
  manifest=$(fetch "$RELEASES/latest/download/$manifest")
  version=$(sed -n 's/^version: *//p' <<<"$manifest" | head -n 1)
  path=$(sed -n 's/^path: *//p' <<<"$manifest" | head -n 1)
  sha512=$(sed -n 's/^sha512: *//p' <<<"$manifest" | head -n 1)
  size=$(sed -n 's/^ *size: *//p' <<<"$manifest" | head -n 1)
  [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "The release manifest has no valid version."
  [ "$path" = "OpenBot-$version-$architecture.AppImage" ] || fail "The release manifest names another file."
  [[ $sha512 =~ ^[A-Za-z0-9+/]{86}==$ ]] || fail "The release manifest has no valid SHA-512."
  if [ "$(staged_version)" != "$version" ]; then rm -rf "$INSTALL/staged" "$INSTALL/staged.ready"; fi
  current=$(version_of "$INSTALL/app")
  [ -n "$current" ] || fail "The installed version is not known."
  newer "$version" "$current" || return 0
  [ -d "$INSTALL/staged" ] && return 0
  echo "Staging OpenBot $version (installed: ${current:-unknown})."
  work=$(mktemp -d "$SCRATCH/openbot-update.XXXXXX")
  trap 'rm -rf "$work"; rm -f "$STATE"' EXIT
  download "$RELEASES/download/v$version/$path" "$work/OpenBot.AppImage" "$size"
  set_state preparing
  [ "$(openssl dgst -sha512 -binary "$work/OpenBot.AppImage" | openssl base64 -A)" = "$sha512" ] ||
    fail "The AppImage does not match the release manifest."
  unpack "$work/OpenBot.AppImage"
  [ "$(version_of "$work/squashfs-root")" = "$version" ] || fail "The AppImage has another version."
  local file
  for file in "${RELEASE_FILES[@]}"; do
    [ -f "$work/squashfs-root/resources/hosting/$file" ] || fail "The release has no hosting files."
  done
  prepare_release "$work/squashfs-root"
  install_packages "$work/squashfs-root/resources/hosting/packages.txt"
  install_optional_packages "$work/squashfs-root/resources/hosting/optional-packages.txt"
  stage_release "$work/squashfs-root"
  echo "OpenBot $version starts at the next start of the server."
}

apply() {
  recover
  local staged current
  staged=$(staged_version)
  if [ -z "$staged" ]; then
    if [ -d "$INSTALL/staged" ]; then echo "The staged release is not complete." >&2; fi
    return 0
  fi
  current=$(version_of "$INSTALL/app")
  if [ ! -e "$INSTALL/.applying" ] && [ -d "$INSTALL/app" ] && ! newer "$staged" "$current"; then
    rm -rf "$INSTALL/staged" "$INSTALL/staged.ready"
    return 0
  fi
  swap_in
  install_hosting "$INSTALL/app/resources/hosting"
  finish_swap
  echo "Updated OpenBot from ${current:-unknown} to $staged."
}

boot() {
  local pid
  pid=$(systemctl show --property=MainPID --value openbot.service || true)
  if [ "${pid:-0}" != 0 ]; then
    return 0
  elif [ -e "$INSTALL/.applying" ]; then
    wait_for_restore
  elif [ ! -e "$INSTALL/staged.ready" ] || restoring; then
    recover
    return 0
  fi
  apply
}

install_missing_hosted_files() {
  local source=$1 file
  for file in "${HOSTED_FILES[@]}"; do
    if [ ! -e "$INSTALL/hosted/$file" ] && [ -f "$source/$file" ]; then
      install_hosted_file "$source" "$file"
    fi
  done
}

trigger() {
  local source=$INSTALL/app/resources/hosting unit changed=0
  repair_release_modes || echo "The modes of the release are not repaired." >&2
  install_missing_hosted_files "$source" || echo "The server files of the release are not installed." >&2
  for unit in "${REQUEST_UNITS[@]}"; do
    if [ ! -e "$UNIT_DIRECTORY/$unit" ] && [ -f "$source/$unit" ]; then
      install -m 0644 "$source/$unit" "$UNIT_DIRECTORY/$unit"
      changed=1
    fi
  done
  if [ "$changed" -eq 1 ]; then
    systemctl daemon-reload
    systemctl enable --quiet openbot-update-request.path
  fi
  install_pre_stop "$source" || echo "The boat pre-stop hook is not installed." >&2
  install_boat_ignore || echo "The boat ignore file is not installed." >&2
  remove_lazy_harnesses || echo "The install-on-first-run agent commands of boat are not removed." >&2
  if command -v apparmor_parser >/dev/null && [ -d /sys/kernel/security/apparmor ]; then
    allow_sandbox_capabilities || echo "The AppArmor rule for the Claude sandbox is not installed." >&2
  fi
  [ -e "$UNIT_DIRECTORY/openbot-update-request.path" ] || return 0
  systemctl is-active --quiet openbot-update-request.path ||
    systemctl start --no-block openbot-update-request.path
}

request() {
  local install=0 status=0 keeper
  if [ -e "$REQUESTS/update-install" ] || [ -L "$REQUESTS/update-install" ]; then install=1; fi
  if [ "$install" -eq 1 ]; then set_state installing; else set_state waiting; fi
  rm -f -- "$REQUESTS/update-stage" "$REQUESTS/update-install"
  (while sleep 5; do touch "$STATE"; done) >/dev/null 2>&1 &
  keeper=$!
  "$INSTALL/hosted/openbot-hosted-update" stage || status=$?
  if [ "$install" -eq 1 ]; then
    status=0
    trap '[ ! -e "$INSTALL/.applying" ] || "$INSTALL/hosted/openbot-hosted-update" apply || true
      systemctl start --no-block openbot.service' EXIT
    trap 'exit 1' TERM
    if systemctl stop openbot.service; then
      "$INSTALL/hosted/openbot-hosted-update" apply || status=$?
    else
      status=1
    fi
  fi
  kill "$keeper" 2>/dev/null || true
  rm -f "$STATE"
  return "$status"
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
  [ "$(id -u)" -eq 0 ] || fail "Run this as root."
  case ${1:-} in
    trigger)
      trigger
      exit 0
      ;;
    request)
      request
      exit 0
      ;;
  esac
  exec 9>"$LOCK"
  flock 9
  if [ "${1:-}" = boot ]; then
    boot
    exit 0
  fi
  if [ "${1:-}" = apply ] && [ ! -e "$INSTALL/staged.ready" ] && [ ! -e "$INSTALL/.applying" ]; then
    recover
    exit 0
  fi
  wait_for_restore
  case ${1:-} in
    stage) stage ;;
    check) check ;;
    apply) apply ;;
    *) fail "usage: $0 boot|stage|check|apply|request|trigger" ;;
  esac
fi
