#!/usr/bin/env bash
# Apply AnvilTermOffice branding to a NATIVE Document Server install.
#
# The docker image bakes branding in at build time (office/docker/Dockerfile),
# so containers are always branded. A native install has no such hook: every
# `dpkg` reinstall restores the stock ONLYOFFICE logos, so the repair path has
# to re-apply this. Idempotent — safe to run on every repair/switch.
#
# Assets are looked up next to this script (repo layout) or in the shared dir
# that enable-oneclick.sh installs them to (root layout).
set -uo pipefail
[ "${1:-}" = "--check" ] && exit 0

WEBAPPS=/var/www/onlyoffice/documentserver/web-apps/apps
HERE="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

# the asset files under /var/www are root-owned; without this the cp/gzip below
# fail one by one and we would still cheerfully report "branding applied"
[ "$(id -u)" = 0 ] || { echo "== branding needs root — skipped"; exit 0; }

for dir in "$HERE/../docker" /usr/local/share/anvilterm-office; do
  [ -f "$dir/header-logo_s.svg" ] && { ASSETS="$dir"; break; }
done
if [ -z "${ASSETS:-}" ]; then
  echo "== branding assets not found — leaving stock ONLYOFFICE logos"
  exit 0
fi
[ -d "$WEBAPPS" ] || { echo "== no native documentserver at $WEBAPPS — nothing to brand"; exit 0; }

echo "== applying AnvilTermOffice branding (assets: $ASSETS)"
for f in header-logo_s.svg dark-logo_s.svg; do
  DEST="$WEBAPPS/common/main/resources/img/header/$f"
  [ -f "$DEST" ] || continue
  # keep exactly one pristine copy, from before we ever touched it
  [ -f "$DEST.orig" ] || cp "$DEST" "$DEST.orig"
  cp "$ASSETS/$f" "$DEST"
  gzip -kf9 "$DEST"
done

# nginx serves the pre-gzipped .css.gz, so the rule must be appended BEFORE
# gzipping, and only once (grep guard) or it stacks up on every repair
RULE='#header-logo{pointer-events:none}#header-logo i{width:140px!important;min-width:140px}.box-tabs .extra.left{flex-shrink:0}'
for ed in presentationeditor documenteditor spreadsheeteditor pdfeditor visioeditor; do
  CSS="$WEBAPPS/$ed/main/resources/css/app.css"
  [ -f "$CSS" ] || continue
  grep -q 'AnvilTermOffice-brand' "$CSS" || printf '\n/*AnvilTermOffice-brand*/%s\n' "$RULE" >> "$CSS"
  gzip -kf9 "$CSS"
done

echo "== branding applied"
