#!/usr/bin/env sh
# Sets up the laptop's virtual camera, "UniConn Camera", once (ADR-0032).
#
# The phone's camera reaches applications on this laptop through a
# v4l2loopback device, and loading a kernel module needs root. UniConn itself
# never runs as root and never asks for it; this script is what the owner
# runs, once, with sudo:
#
#   sudo scripts/install-linux-webcam.sh           # set up, and at every boot
#   sudo scripts/install-linux-webcam.sh --remove  # undo it
#
# It changes nothing if another v4l2loopback set-up is already there (OBS
# Studio's virtual camera is one), because taking that device over would
# break it; it says so and stops instead.
set -eu

label="UniConn Camera"
number=42
options=/etc/modprobe.d/uniconn-webcam.conf
autoload=/etc/modules-load.d/uniconn-webcam.conf
rule=/etc/udev/rules.d/70-uniconn-webcam.rules

say() { printf '%s\n' "$*"; }
fail() {
  code=$1
  shift
  printf 'uniconn webcam: %s\n' "$*" >&2
  exit "$code"
}

# Whether a loaded device carries our label.
ours_loaded() {
  for name in /sys/class/video4linux/*/name; do
    [ -r "$name" ] && [ "$(cat "$name")" = "$label" ] && return 0
  done
  return 1
}

# How this distribution installs a package, for what is said when one is
# missing: Debian and Ubuntu, Fedora (whose module is in RPM Fusion), Arch.
distribution() {
  ids=$( (. /etc/os-release 2>/dev/null && printf '%s %s' "${ID:-}" "${ID_LIKE:-}") || true)
  case " $ids " in
    *" fedora "*|*" rhel "*) echo fedora ;;
    *" arch "*) echo arch ;;
    *) echo debian ;;
  esac
}
install_hint() {
  case "$(distribution):$1" in
    fedora:module) echo "sudo dnf install akmod-v4l2loopback (from RPM Fusion)" ;;
    fedora:tools) echo "sudo dnf install v4l-utils" ;;
    arch:module) echo "sudo pacman -S v4l2loopback-dkms (with your kernel's headers)" ;;
    arch:tools) echo "sudo pacman -S v4l-utils" ;;
    *:module) echo "sudo apt install v4l2loopback-dkms" ;;
    *:tools) echo "sudo apt install v4l-utils" ;;
  esac
}

[ "$(id -u)" = 0 ] || fail 1 "run this with sudo; it loads a kernel module"

case "${1:-}" in
  "") ;;
  --remove)
    rm -f "$options" "$autoload" "$rule"
    command -v udevadm >/dev/null 2>&1 && udevadm control --reload-rules
    if ours_loaded; then
      if modprobe -r v4l2loopback 2>/dev/null; then
        say "Removed UniConn Camera."
      else
        say "Removed the set-up; the device goes at the next boot (an application is using it now)."
      fi
    else
      say "Removed the set-up."
    fi
    exit 0
    ;;
  *) fail 64 "usage: $0 [--remove]" ;;
esac

modinfo v4l2loopback >/dev/null 2>&1 ||
  fail 2 "this kernel has no v4l2loopback module; install it with '$(install_hint module)' and run this again"

# Someone else's v4l2loopback options would fight ours at the next boot.
for file in /etc/modprobe.d/*.conf; do
  [ -e "$file" ] || continue
  [ "$file" = "$options" ] && continue
  if grep -qs '^[[:space:]]*options[[:space:]]\+v4l2loopback' "$file"; then
    fail 3 "$file already sets up v4l2loopback (perhaps for OBS Studio); UniConn will not take it over. Remove that file, or add card_label=\"$label\" to it yourself, then run this again"
  fi
done
if lsmod | grep -q '^v4l2loopback ' && ! ours_loaded; then
  fail 3 "v4l2loopback is already loaded for something else (perhaps OBS Studio's virtual camera); close it, or run 'sudo modprobe -r v4l2loopback', then run this again"
fi
if [ -e "/dev/video$number" ] && ! ours_loaded; then
  fail 3 "/dev/video$number is already another camera; UniConn will not take it over"
fi

umask 022
cat >"$options" <<EOF
# UniConn Camera: the phone's camera as this laptop's webcam (ADR-0032).
# exclusive_caps lets browsers see it; two buffers keep it live, not late.
options v4l2loopback devices=1 video_nr=$number card_label="$label" exclusive_caps=1 max_buffers=2
EOF
cat >"$autoload" <<EOF
# UniConn Camera (ADR-0032).
v4l2loopback
EOF

# The controls that keep an application's camera open across a gap: the
# device keeps its format with no writer, and repeats the last frame rather
# than stopping. They are the module's own, so v4l2-ctl sets them. The
# packages bring v4l2-ctl; wanted, not needed: without it the camera works
# and an application may show an error rather than the last picture when a
# session pauses.
if ! command -v v4l2-ctl >/dev/null 2>&1; then
  say "v4l2-ctl is missing; UniConn Camera works without it. Add it with '$(install_hint tools)' and run this again."
fi
ctl=$(command -v v4l2-ctl || true)
if [ -n "$ctl" ]; then
  cat >"$rule" <<EOF
# UniConn Camera (ADR-0032): keep the format and the last frame across a gap.
ACTION=="add", SUBSYSTEM=="video4linux", ATTR{name}=="$label", RUN+="$ctl -d \$devnode -c keep_format=1,sustain_framerate=1"
EOF
  command -v udevadm >/dev/null 2>&1 && udevadm control --reload-rules
fi

ours_loaded || modprobe v4l2loopback
ours_loaded || fail 4 "the module loaded but no device is called \"$label\"; run it again after a reboot"
if [ -n "$ctl" ]; then
  "$ctl" -d "/dev/video$number" -c keep_format=1,sustain_framerate=1 ||
    say "Could not set the device's controls now; they are set at the next boot."
fi
say "UniConn Camera is ready at /dev/video$number, now and at every boot."
