#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo "This helper must be run through pkexec." >&2
  exit 77
fi

if ! command -v modprobe >/dev/null 2>&1; then
  echo "modprobe is unavailable on this system." >&2
  exit 69
fi

if [ ! -r /etc/os-release ]; then
  echo "Cannot identify this Linux distribution. LumaLink currently supports Debian only." >&2
  exit 65
fi

# shellcheck disable=SC1091
. /etc/os-release
if [ "${ID:-}" != "debian" ]; then
  echo "LumaLink currently supports Debian only. Detected: ${PRETTY_NAME:-unknown Linux distribution}." >&2
  exit 65
fi

if [ ! -d /sys/module/v4l2loopback ]; then
  if ! command -v apt-get >/dev/null 2>&1; then
    echo "apt-get is unavailable. LumaLink currently supports Debian only." >&2
    exit 65
  fi
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get install -y v4l2loopback-dkms v4l2loopback-utils
fi

modprobe v4l2loopback exclusive_caps=1 card_label="LumaLink Camera"

login_uid=${PKEXEC_UID:-}
if [ -n "$login_uid" ] && command -v getent >/dev/null 2>&1; then
  login_user=$(getent passwd "$login_uid" | cut -d: -f1)
  if [ -n "$login_user" ] && getent group video >/dev/null 2>&1; then
    usermod -aG video "$login_user"
  fi
fi

echo "LumaLink Camera is ready. If it does not appear yet, sign out and back in."
