#!/bin/sh
set -eu
case "${1:-}" in configure|abort-upgrade|abort-remove|abort-deconfigure) ;; *) exit 0;;esac
for path in /opt/screen2screen-linux-host-gui /etc/screen2screen-linux-host-gui /var/lib/screen2screen-linux-host-gui; do
 [ ! -L "$path" ] || { echo 'Screen2Screen: unsafe installation path.' >&2;exit 1; }
done
if ! getent passwd screen2screen-gui >/dev/null; then useradd --system --user-group --home-dir /var/lib/screen2screen-linux-host-gui --shell /usr/sbin/nologin screen2screen-gui;fi
if ! getent passwd screen2screen-gui-render >/dev/null; then useradd --system --user-group --home-dir /nonexistent --shell /usr/sbin/nologin screen2screen-gui-render;fi
[ "$(id -u screen2screen-gui)" != 0 ] && [ "$(id -u screen2screen-gui-render)" != 0 ] && [ "$(id -u screen2screen-gui)" != "$(id -u screen2screen-gui-render)" ] || exit 1
install -d -m 0700 -o screen2screen-gui -g screen2screen-gui /var/lib/screen2screen-linux-host-gui
# Remove only byte-identical files from the prior tar.gz installer. Keep custom
# administrator overrides; do not touch their pairing data or GDM settings.
while read -r expected path; do
 if [ -f "$path" ] && [ ! -L "$path" ]; then
  actual=$(sha256sum "$path");actual=${actual%% *}
  if grep -Fqx "$actual $path" /opt/screen2screen-linux-host-gui/packaging/legacy-files.sha256;then rm -f -- "$path";
  else printf 'Screen2Screen: preserved custom legacy file %s; review it after upgrade.\n' "$path" >&2;fi
 fi
done < /opt/screen2screen-linux-host-gui/packaging/legacy-files.sha256
if [ -f /var/lib/screen2screen-linux-host-gui/settings.json ]; then
 capture_backend=$(cat /etc/screen2screen-linux-host-gui/capture-backend)
 case "$capture_backend" in auto|drm|gnome) ;; *) echo 'Screen2Screen: invalid capture-backend setting.' >&2;exit 1;;esac
 # Reapply reviewed device permissions only for a previously authorized install.
 # Never start package-manager operations or prompt from a maintainer script.
 bash -c '. /opt/screen2screen-linux-host-gui/scripts/drm-install.sh; s2s_configure_drm "$1"' sh "$capture_backend"
fi
/opt/screen2screen-linux-host-gui/packaging/package-state.sh restore
if [ ! -f /var/lib/screen2screen-linux-host-gui/settings.json ];then
 echo 'Screen2Screen installed. Authorize and pair: sudo screen2screen-linux-host-gui setup --joincode'
fi
echo 'Unpair online before removing/purging to release its organization device allowance.'
