#!/usr/bin/env bash
# AnvilTermOffice Document Server repair — installed root-owned at
# /usr/local/sbin/anvilterm-office-repair and whitelisted in sudoers so the
# app can run it WITHOUT a password. Fixed logic, no arguments accepted
# (except --check), so the sudo grant cannot be abused to run anything else.
set -uo pipefail
[ "${1:-}" = "--check" ] && exit 0
if [ "${1:-}" = "--cancel" ]; then
  # explicit user request — unlike auto-heal, this MAY kill a healthy install.
  # It must also reap the slow postinst children (allthemesgen / allfontsgen),
  # or "cancel" leaves them running and the next run trips over them.
  echo "== cancelling document server install/repair"
  pkill -9 -f "onlyoffice-documentserver.postinst" 2>/dev/null
  pkill -9 -f "allthemesgen|allfontsgen|documentserver-generate" 2>/dev/null
  pkill -9 -f "dpkg -i.*onlyoffice-documentserver" 2>/dev/null
  pkill -9 -f "apt-get install" 2>/dev/null
  # kill other running instances of this script (not ourselves)
  for pid in $(pgrep -f "bash /usr/local/sbin/anvilterm-office-repair$"); do
    [ "$pid" != "$$" ] && kill -9 "$pid" 2>/dev/null
  done
  rm -f /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null
  echo "== cancelled"
  exit 0
fi
export DEBIAN_FRONTEND=noninteractive

# Every process the DS install legitimately runs. `dpkg -i` shows up as argv[0]
# "dpkg", and the slow tail of the postinst is allthemesgen / allfontsgen —
# none of which matched the old "wedged" patterns.
INSTALL_PROCS='onlyoffice-documentserver\.postinst|allthemesgen|allfontsgen|documentserver-generate|dpkg --status-fd|(^|/)dpkg -i|apt-get install'

# Sum CPU-seconds burnt by the install right now. Growing = doing real work.
install_cpu() {
  local total=0 t
  for p in $(pgrep -f "$INSTALL_PROCS" 2>/dev/null); do
    t=$(ps -o cputimes= -p "$p" 2>/dev/null | tr -d ' ')
    [ -n "$t" ] && total=$(( total + t ))
  done
  echo "$total"
}

echo "== stopping the docker Document Server (mutual exclusion on ports)"
docker stop onlyoffice 2>/dev/null || true

# NEVER kill an install that is making progress. Generating fonts, themes and
# js caches takes many minutes on WSL and prints nothing while it works — the
# old blind pkill shot it dead one line before "Congratulations", leaving the
# package half-configured, which made the app run this script again. That loop
# is what "dpkg was interrupted" actually was.
if pgrep -f "$INSTALL_PROCS" >/dev/null 2>&1; then
  echo "== an install is already running — checking whether it is progressing"
  before=$(install_cpu); sleep 12; after=$(install_cpu)
  if [ "$after" -gt "$before" ]; then
    echo "== it burnt $(( after - before ))s of CPU in 12s: healthy, just slow."
    echo "== refusing to interrupt it. Let it finish (fonts/themes take minutes)."
    exit 4
  fi
  echo "== no CPU progress in 12s — genuinely wedged, clearing it"
  pkill -9 -f "$INSTALL_PROCS" 2>/dev/null
  sleep 1
  # only safe once nothing holds them: deleting live locks corrupts the db
  rm -f /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/cache/apt/archives/lock 2>/dev/null
fi

# an interrupted run leaves the database half-configured; finish it before
# reaching for a reinstall (cheap, and usually all that is needed)
if dpkg-query -W -f='${db:Status-Abbrev}' onlyoffice-documentserver 2>/dev/null | grep -q '^i[^i]'; then
  echo "== finishing the interrupted configure (this is the slow part)"
  dpkg --configure -a --force-confdef --force-confold || true
fi

st=$(dpkg-query -W -f='${db:Status-Abbrev}' onlyoffice-documentserver 2>/dev/null || true)
echo "== package state: ${st:-absent}"

if [ -z "$st" ]; then
  echo "== not installed — running full installer"
  exec bash "$(dirname "$(readlink -f "$0")")/install-ds-ubuntu.sh" 2>/dev/null || {
    echo "installer not found next to repair script; install manually"; exit 1; }
fi

echo "== refreshing package lists"
apt-get update -qq || true

# an interrupted install can destroy conffiles of DEPENDENCY packages too —
# a missing /etc/nginx/nginx.conf kills the DS configure at its last step.
# (package naming differs per distro: nginx.conf lives in `nginx` on Ubuntu
# 24.04, `nginx-common` on Debian/older — reinstall whichever is installed)
if [ ! -f /etc/nginx/nginx.conf ]; then
  echo "== nginx config missing (damaged by an interrupted install) — repairing nginx"
  dpkg --configure -a --force-confdef --force-confold 2>/dev/null || true
  NGINX_PKGS=""
  for pkg in nginx nginx-common nginx-core; do
    dpkg -s "$pkg" >/dev/null 2>&1 && NGINX_PKGS="$NGINX_PKGS $pkg"
  done
  if [ -n "$NGINX_PKGS" ]; then
    apt-get install --reinstall -y \
      -o Dpkg::Use-Pty=0 \
      -o Dpkg::Options::=--force-confmiss \
      -o Dpkg::Options::=--force-confdef \
      $NGINX_PKGS || true
  fi
fi

# a fully-configured package needs no 700MB reinstall — the usual "broken DS"
# is a service problem, not a file problem
st=$(dpkg-query -W -f='${db:Status-Abbrev}' onlyoffice-documentserver 2>/dev/null || true)
if [ "${st:0:2}" = "ii" ] && [ -f /etc/onlyoffice/documentserver/nginx/ds.conf.tmpl ]; then
  echo "== package is fully configured — skipping reinstall, repairing services only"
else
  echo "== reinstalling package (re-extracts any missing files)"
  if ! apt-get install --reinstall -y \
    -o Dpkg::Use-Pty=0 \
    -o Dpkg::Options::=--force-confdef \
    -o Dpkg::Options::=--force-confmiss \
    onlyoffice-documentserver; then
    echo "== reinstall failed — downloading the package directly"
    tmp=$(mktemp -d); cd "$tmp"
    apt-get download onlyoffice-documentserver
    dpkg -i --force-confmiss --force-confdef ./onlyoffice-documentserver*.deb
    cd /; rm -rf "$tmp"
  fi
fi

# One owner per service. With systemd present the .deb ships ds-*.service; a
# leftover supervisor ds.conf from a pre-systemd install ALSO spawns them, and
# the loser crash-loops on :8000. `supervisorctl restart all` used to be right
# here — it was starting the duplicate this script was called to fix.
if [ -d /run/systemd/system ] && [ -f /etc/supervisor/conf.d/ds.conf ]; then
  echo "== retiring stale supervisor ds.conf (systemd owns the DS units now)"
  supervisorctl stop ds-docservice ds-converter 2>/dev/null
  mv /etc/supervisor/conf.d/ds.conf /etc/supervisor/conf.d/ds.conf.disabled
  supervisorctl reread 2>/dev/null
  supervisorctl update 2>/dev/null
fi

# A reinstall rewrites local.json back to allowPrivateIPAddress=false, and the
# DS then refuses to download the document from the engine on 127.0.0.1 —
# the editor reports "download failed" while every service looks healthy.
if [ -f /etc/onlyoffice/documentserver/local.json ]; then
  python3 - <<'PY' || echo "!! could not patch local.json — private-IP downloads may fail"
import json, shutil
p = '/etc/onlyoffice/documentserver/local.json'
d = json.load(open(p))
co = d.setdefault('services', {}).setdefault('CoAuthoring', {})
rfa = co.get('request-filtering-agent') or {}
if not (rfa.get('allowPrivateIPAddress') and rfa.get('allowMetaIPAddress')):
    shutil.copy(p, p + '.bak')
    co['request-filtering-agent'] = {'allowPrivateIPAddress': True, 'allowMetaIPAddress': True}
    json.dump(d, open(p, 'w'), indent=2)
    print('== allowed private-IP downloads (engine runs on 127.0.0.1)')
else:
    print('== private-IP downloads already allowed')
PY
fi

# a reinstall restores the stock ONLYOFFICE logos over the AnvilTerm branding
for b in /usr/local/sbin/anvilterm-office-brand \
         "$(dirname "$(readlink -f "$0")")/anvilterm-office-brand"; do
  [ -x "$b" ] && { bash "$b"; break; }
done

echo "== restarting services"
# `enable`, not just `restart`: the postinst starts nginx but never enables it,
# and use-docker may have disabled it — either way it must survive a reboot
systemctl enable --now postgresql rabbitmq-server 2>/dev/null || true
systemctl enable --now nginx 2>/dev/null || true
systemctl restart nginx 2>/dev/null || true
systemctl enable ds-docservice ds-converter 2>/dev/null || true
systemctl restart ds-converter ds-docservice 2>/dev/null || true

sleep 5
if curl -sf http://127.0.0.1/healthcheck >/dev/null 2>&1; then
  echo "== REPAIR SUCCESSFUL — Document Server is up"
else
  echo "== repair finished; server still warming up (check again in ~30s)"
fi
