#!/usr/bin/env bash
set -euo pipefail

STATE_DIR=/var/lib/brz-healthos
CACHE_DIR=/var/cache/brz-healthos
MARKER="$STATE_DIR/workstation-apps-0.8.0.provisioned"

ONLYOFFICE_VERSION='9.4.0'
RUSTDESK_VERSION='1.4.9'

mkdir -p "$STATE_DIR" "$CACHE_DIR"

ARCH="$(dpkg --print-architecture)"
case "$ARCH" in
  amd64)
    ONLYOFFICE_KIND=deb
    ONLYOFFICE_URL="https://github.com/ONLYOFFICE/DesktopEditors/releases/download/v${ONLYOFFICE_VERSION}/onlyoffice-desktopeditors_amd64.deb"
    ONLYOFFICE_SHA256='4271434e81be42b1559fd989d24bf6d413482f278dc6a5e328202a4fc1a18649'
    ONLYOFFICE_FILE="$CACHE_DIR/onlyoffice-desktopeditors_amd64.deb"
    RUSTDESK_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/rustdesk-${RUSTDESK_VERSION}-x86_64.deb"
    RUSTDESK_SHA256='7244ba47c40e804172044bfbe659467c54ce46554c98e78c8c0406f1d612fda3'
    RUSTDESK_DEB="$CACHE_DIR/rustdesk-${RUSTDESK_VERSION}-x86_64.deb"
    ;;
  arm64)
    ONLYOFFICE_KIND=appimage
    ONLYOFFICE_URL="https://github.com/ONLYOFFICE/DesktopEditors/releases/download/v${ONLYOFFICE_VERSION}/DesktopEditors-arm64.AppImage"
    ONLYOFFICE_SHA256='7dfc2fa195ff9912a4022841613b9a99fdba2a238792648f257007a7df887b7c'
    ONLYOFFICE_FILE="$CACHE_DIR/DesktopEditors-${ONLYOFFICE_VERSION}-arm64.AppImage"
    RUSTDESK_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/rustdesk-${RUSTDESK_VERSION}-aarch64.deb"
    RUSTDESK_SHA256='ce62c996f14d33f3bbe3a330e953644a44bace7f05885a7953f7395d69fb49c0'
    RUSTDESK_DEB="$CACHE_DIR/rustdesk-${RUSTDESK_VERSION}-aarch64.deb"
    ;;
  *)
    logger -t brz-healthos "Unsupported workstation architecture: $ARCH" || true
    exit 1
    ;;
esac

fetch_deb() {
  local url="$1" sha="$2" dest="$3"
  if [[ -f "$dest" ]] && printf '%s  %s\n' "$sha" "$dest" | sha256sum -c - >/dev/null 2>&1; then
    return 0
  fi
  rm -f "$dest.tmp"
  curl --fail --location --silent --show-error --retry 4 --retry-delay 3 "$url" -o "$dest.tmp"
  printf '%s  %s\n' "$sha" "$dest.tmp" | sha256sum -c -
  mv "$dest.tmp" "$dest"
}

onlyoffice_ok=false
rustdesk_ok=false

if command -v desktopeditors >/dev/null 2>&1 || dpkg-query -W -f='${Status}' onlyoffice-desktopeditors 2>/dev/null | grep -q 'install ok installed'; then
  onlyoffice_ok=true
else
  if fetch_deb "$ONLYOFFICE_URL" "$ONLYOFFICE_SHA256" "$ONLYOFFICE_FILE"; then
    if [[ "$ONLYOFFICE_KIND" == deb ]]; then
      apt-get update -qq || true
      DEBIAN_FRONTEND=noninteractive apt-get install -y "$ONLYOFFICE_FILE" && onlyoffice_ok=true || true
    else
      extract_dir="$(mktemp -d "$CACHE_DIR/onlyoffice-extract.XXXXXX")"
      chmod 0755 "$ONLYOFFICE_FILE"
      if (cd "$extract_dir" && "$ONLYOFFICE_FILE" --appimage-extract >/dev/null); then
        rm -rf /opt/brz-healthos/onlyoffice-desktopeditors
        install -d -m 0755 /opt/brz-healthos
        mv "$extract_dir/squashfs-root" /opt/brz-healthos/onlyoffice-desktopeditors
        ln -sfn /opt/brz-healthos/onlyoffice-desktopeditors/AppRun /usr/local/bin/desktopeditors
        cat >/usr/share/applications/onlyoffice-desktopeditors.desktop <<'DESKTOP'
[Desktop Entry]
Type=Application
Name=ONLYOFFICE Desktop Editors
Comment=Edit documents, spreadsheets, and presentations
Exec=/usr/local/bin/desktopeditors %U
Icon=/opt/brz-healthos/onlyoffice-desktopeditors/onlyoffice-desktopeditors.png
Terminal=false
Categories=Office;WordProcessor;Spreadsheet;Presentation;
MimeType=application/vnd.openxmlformats-officedocument.wordprocessingml.document;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;application/vnd.openxmlformats-officedocument.presentationml.presentation;
DESKTOP
        chmod 0644 /usr/share/applications/onlyoffice-desktopeditors.desktop
        update-desktop-database -q /usr/share/applications 2>/dev/null || true
        onlyoffice_ok=true
      fi
      rm -rf "$extract_dir"
    fi
  fi
fi

if command -v rustdesk >/dev/null 2>&1 || dpkg-query -W -f='${Status}' rustdesk 2>/dev/null | grep -q 'install ok installed'; then
  rustdesk_ok=true
else
  if fetch_deb "$RUSTDESK_URL" "$RUSTDESK_SHA256" "$RUSTDESK_DEB"; then
    apt-get update -qq || true
    DEBIAN_FRONTEND=noninteractive apt-get install -y "$RUSTDESK_DEB" && rustdesk_ok=true || true
  fi
fi

if "$onlyoffice_ok" && "$rustdesk_ok"; then
  touch "$MARKER"
  logger -t brz-healthos 'Workstation apps provisioned: ONLYOFFICE Desktop Editors and RustDesk.' || true
  exit 0
fi

logger -t brz-healthos "Workstation app provisioning incomplete: onlyoffice=$onlyoffice_ok rustdesk=$rustdesk_ok" || true
exit 1
