#!/usr/bin/env bash
# Provision the private DRM outputs used by Vibeshine's Linux virtual-display
# backend. This helper is intentionally root-run: mounting configfs, loading
# VKMS, and changing configfs objects are privileged operations.

set -uo pipefail

PROGRAM_NAME="vibeshine-vkms"
VKMS_DEVICE_NAME="vibeshine"
VKMS_OUTPUT_COUNT=4
DRM_MODULE="vibeshine_drm"
DRM_BACKEND="vibeshine-drm"
CONNECTOR_STATUS_CONNECTED=1
CONNECTOR_STATUS_DISCONNECTED=2

# These are reset to the production path by main(). Keeping path setup in one
# function lets the shell tests source this file and use a disposable tree.
CONFIGFS_MOUNTPOINT=""
VKMS_CONFIGFS_ROOT=""
VKMS_DEVICE_DIR=""
LEASE_ROOT=""
FAKE_CONFIGFS=0

log() {
  printf '%s: %s\n' "$PROGRAM_NAME" "$*"
}

error() {
  printf '%s: error: %s\n' "$PROGRAM_NAME" "$*" >&2
}

configure_paths() {
  local configfs_mountpoint=$1

  CONFIGFS_MOUNTPOINT=$configfs_mountpoint
  VKMS_CONFIGFS_ROOT="${CONFIGFS_MOUNTPOINT}/${DRM_BACKEND}"
  VKMS_DEVICE_DIR="${VKMS_CONFIGFS_ROOT}/${VKMS_DEVICE_NAME}"
}

configure_lease_paths() {
  LEASE_ROOT=$1
}

require_root() {
  if ((EUID != 0)); then
    error "this action must be run as root"
    return 1
  fi
}

require_command() {
  local command_name=$1

  if ! command -v "$command_name" >/dev/null 2>&1; then
    error "required command not found: ${command_name}"
    return 1
  fi
}

configfs_is_mounted() {
  # mountinfo field 5 is the mount point and the filesystem type follows the
  # " - " separator. The production path contains no mountinfo escapes.
  awk -v target="$CONFIGFS_MOUNTPOINT" '
    $5 == target {
      for (i = 6; i <= NF; ++i) {
        if ($i == "-" && $(i + 1) == "configfs") {
          found = 1
        }
      }
    }
    END { exit(found ? 0 : 1) }
  ' /proc/self/mountinfo
}

ensure_configfs() {
  if configfs_is_mounted; then
    return 0
  fi

  if [[ ! -d "$CONFIGFS_MOUNTPOINT" ]]; then
    error "configfs mount point is unavailable: ${CONFIGFS_MOUNTPOINT}"
    return 1
  fi

  log "mounting configfs at ${CONFIGFS_MOUNTPOINT}"
  if ! mount -t configfs configfs "$CONFIGFS_MOUNTPOINT"; then
    error "could not mount configfs; ensure the kernel supports CONFIG_CONFIGFS_FS"
    return 1
  fi

  if ! configfs_is_mounted; then
    error "${CONFIGFS_MOUNTPOINT} is not a configfs mount after mount completed"
    return 1
  fi
}

ensure_display_backend() {
  if [[ -d "$VKMS_CONFIGFS_ROOT" ]]; then
    log "using Vibeshine DRM HDR virtual-display backend"
    return 0
  fi

  log "loading the Vibeshine DRM HDR virtual-display module"
  if ! modprobe "$DRM_MODULE" create_default_dev=0; then
    error "${DRM_MODULE} is unavailable; refusing CPU-backed stock VKMS fallback"
    return 1
  fi
  if [[ ! -d "$VKMS_CONFIGFS_ROOT" ]]; then
    error "${DRM_MODULE} loaded without its expected configfs subsystem at ${VKMS_CONFIGFS_ROOT}"
    return 1
  fi
  log "using Vibeshine DRM HDR virtual-display backend"
}

write_attribute() {
  local path=$1
  local value=$2

  if ! printf '%s\n' "$value" >"$path"; then
    error "could not write '${value}' to ${path}"
    return 1
  fi
}

attribute_equals() {
  local path=$1
  local expected=$2
  local actual

  if [[ ! -f "$path" ]]; then
    error "required VKMS attribute is missing: ${path}"
    return 1
  fi

  actual=$(<"$path")
  if [[ "$actual" != "$expected" ]]; then
    error "unexpected value in ${path}: expected '${expected}', found '${actual}'"
    return 1
  fi
}

attribute_is_connection_state() {
  local path=$1
  local actual

  if [[ ! -f "$path" || -L "$path" ]]; then
    error "required VKMS connector status is missing or unsafe: ${path}"
    return 1
  fi

  actual=$(<"$path")
  case "$actual" in
    "$CONNECTOR_STATUS_CONNECTED" | "$CONNECTOR_STATUS_DISCONNECTED")
      return 0
      ;;
    *)
      error "unexpected connector status in ${path}: '${actual}'"
      return 1
      ;;
  esac
}

create_configfs_item() {
  local path=$1
  local kind=$2

  if ! mkdir -- "$path"; then
    error "could not create VKMS ${kind}: ${path}"
    return 1
  fi

  # A real configfs item creates its attributes and link groups in the kernel.
  # The sourced shell test enables this branch to model those generated nodes.
  if ((FAKE_CONFIGFS)); then
    case "$kind" in
      device)
        mkdir -- "$path/planes" "$path/crtcs" "$path/encoders" "$path/connectors" || return 1
        printf '0' >"$path/enabled" || return 1
        ;;
      plane)
        mkdir -- "$path/possible_crtcs" || return 1
        : >"$path/type" || return 1
        ;;
      crtc)
        : >"$path/writeback" || return 1
        ;;
      encoder)
        mkdir -- "$path/possible_crtcs" || return 1
        ;;
      connector)
        mkdir -- "$path/possible_encoders" || return 1
        : >"$path/status" || return 1
        printf '0 0 0\n' >"$path/requested_mode" || return 1
        ;;
      *)
        error "internal error: unknown configfs item kind '${kind}'"
        return 1
        ;;
    esac
  fi
}

validate_device_layout() {
  local group

  if [[ ! -d "$VKMS_DEVICE_DIR" || -L "$VKMS_DEVICE_DIR" ||
        ! -f "$VKMS_DEVICE_DIR/enabled" || -L "$VKMS_DEVICE_DIR/enabled" ]]; then
    error "VKMS did not create the expected configfs device layout"
    return 1
  fi

  for group in planes crtcs encoders connectors; do
    if [[ ! -d "$VKMS_DEVICE_DIR/$group" || -L "$VKMS_DEVICE_DIR/$group" ]]; then
      error "VKMS configfs group is missing: ${VKMS_DEVICE_DIR}/${group}"
      return 1
    fi
  done
}

resource_name_is_managed() {
  local group=$1
  local name=$2
  local index

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    case "$group:$name" in
      "planes:plane${index}" | "crtcs:crtc${index}" | "encoders:encoder${index}")
        return 0
        ;;
      "connectors:Virtual-$((index + 1))")
        return 0
        ;;
    esac
  done
  return 1
}

link_directory_is_managed() {
  local directory=$1
  local expected_name=$2
  local entry name

  [[ -e "$directory" || -L "$directory" ]] || return 0
  if [[ ! -d "$directory" || -L "$directory" ]]; then
    error "refusing cleanup because the VKMS link group is not a directory: ${directory}"
    return 1
  fi
  for entry in "$directory"/*; do
    [[ -e "$entry" || -L "$entry" ]] || continue
    name=${entry##*/}
    if [[ "$name" != "$expected_name" ]]; then
      error "refusing cleanup because ${directory} contains unmanaged entry '${name}'"
      return 1
    fi
  done
}

cleanup_is_safe() {
  local group group_dir entry name index

  # Cleanup never accepts a caller-provided instance name and only works below
  # the path derived from the fixed "vibeshine" instance identifier.
  if [[ "$VKMS_DEVICE_DIR" != "${VKMS_CONFIGFS_ROOT}/${VKMS_DEVICE_NAME}" ]]; then
    error "refusing cleanup of unexpected path: ${VKMS_DEVICE_DIR}"
    return 1
  fi
  if [[ -L "$VKMS_DEVICE_DIR" ]]; then
    error "refusing cleanup because the managed instance path is a symbolic link"
    return 1
  fi
  if [[ -L "$VKMS_DEVICE_DIR/enabled" ]]; then
    error "refusing cleanup because the managed enabled attribute is a symbolic link"
    return 1
  fi

  for group in planes crtcs encoders connectors; do
    group_dir="$VKMS_DEVICE_DIR/$group"
    [[ -e "$group_dir" || -L "$group_dir" ]] || continue
    if [[ ! -d "$group_dir" || -L "$group_dir" ]]; then
      error "refusing cleanup because the VKMS group is not a directory: ${group_dir}"
      return 1
    fi
    for entry in "$group_dir"/*; do
      [[ -e "$entry" || -L "$entry" ]] || continue
      name=${entry##*/}
      if [[ ! -d "$entry" || -L "$entry" ]] || ! resource_name_is_managed "$group" "$name"; then
        error "refusing cleanup because ${group_dir} contains unmanaged entry '${name}'"
        return 1
      fi
    done
  done

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    link_directory_is_managed \
      "$VKMS_DEVICE_DIR/planes/plane${index}/possible_crtcs" "crtc${index}" || return 1
    link_directory_is_managed \
      "$VKMS_DEVICE_DIR/encoders/encoder${index}/possible_crtcs" "crtc${index}" || return 1
    link_directory_is_managed \
      "$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))/possible_encoders" "encoder${index}" || return 1
  done
}

remove_link_if_present() {
  local path=$1

  if [[ -L "$path" ]]; then
    if ! unlink -- "$path"; then
      error "could not remove VKMS link: ${path}"
      return 1
    fi
  elif [[ -e "$path" ]]; then
    error "refusing to unlink non-symbolic-link path: ${path}"
    return 1
  fi
}

prepare_fake_item_for_removal() {
  local path=$1
  local kind=$2

  ((FAKE_CONFIGFS)) || return 0
  case "$kind" in
    plane)
      rm -f -- "$path/type"
      rmdir -- "$path/possible_crtcs" 2>/dev/null || true
      ;;
    crtc)
      rm -f -- "$path/writeback"
      ;;
    encoder)
      rmdir -- "$path/possible_crtcs" 2>/dev/null || true
      ;;
    connector)
      rm -f -- "$path/status"
      rm -f -- "$path/requested_mode"
      rmdir -- "$path/possible_encoders" 2>/dev/null || true
      ;;
  esac
}

remove_configfs_item() {
  local path=$1
  local kind=$2

  [[ -e "$path" || -L "$path" ]] || return 0
  if [[ ! -d "$path" || -L "$path" ]]; then
    error "refusing to remove non-directory VKMS ${kind}: ${path}"
    return 1
  fi
  prepare_fake_item_for_removal "$path" "$kind"
  if ! rmdir -- "$path"; then
    error "could not remove VKMS ${kind}: ${path}"
    return 1
  fi
}

remove_pool() {
  local index rc=0

  if [[ ! -d "$VKMS_DEVICE_DIR" ]]; then
    clear_connector_leases || return 1
    log "${DRM_BACKEND} display pool is already stopped"
    return 0
  fi

  cleanup_is_safe || return 1

  if [[ -f "$VKMS_DEVICE_DIR/enabled" ]]; then
    write_attribute "$VKMS_DEVICE_DIR/enabled" 0 || return 1
  fi

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    remove_link_if_present \
      "$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))/possible_encoders/encoder${index}" || rc=1
    remove_link_if_present \
      "$VKMS_DEVICE_DIR/encoders/encoder${index}/possible_crtcs/crtc${index}" || rc=1
    remove_link_if_present \
      "$VKMS_DEVICE_DIR/planes/plane${index}/possible_crtcs/crtc${index}" || rc=1
  done
  ((rc == 0)) || return "$rc"

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    remove_configfs_item "$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))" connector || rc=1
    remove_configfs_item "$VKMS_DEVICE_DIR/encoders/encoder${index}" encoder || rc=1
    remove_configfs_item "$VKMS_DEVICE_DIR/planes/plane${index}" plane || rc=1
    remove_configfs_item "$VKMS_DEVICE_DIR/crtcs/crtc${index}" crtc || rc=1
  done
  ((rc == 0)) || return "$rc"

  if ((FAKE_CONFIGFS)); then
    rm -f -- "$VKMS_DEVICE_DIR/enabled"
    rmdir -- "$VKMS_DEVICE_DIR/planes" "$VKMS_DEVICE_DIR/crtcs" \
      "$VKMS_DEVICE_DIR/encoders" "$VKMS_DEVICE_DIR/connectors" || return 1
  fi

  if ! rmdir -- "$VKMS_DEVICE_DIR"; then
    error "could not remove VKMS instance: ${VKMS_DEVICE_DIR}"
    return 1
  fi

  clear_connector_leases || return 1

  log "removed private display pool from ${DRM_BACKEND}"
}

system_is_stopping() {
  local state

  state=$(systemctl is-system-running 2>/dev/null || true)
  [[ "$state" == stopping ]]
}

stop_pool() {
  # The system service and the graphical user session stop concurrently during
  # a global shutdown. Tearing down configfs here can unplug the DRM device
  # while KWin still owns it; KWin then closes an already-destroyed modeset
  # device later in shutdown. Keep the device alive for the remaining fraction
  # of userspace shutdown instead. The driver's reboot notifier quiesces it
  # before physical GPU device shutdown. Manual stops still remove the pool.
  if system_is_stopping; then
    log "system shutdown is in progress; preserving the display pool until kernel restart"
    return 0
  fi

  remove_pool
}

validate_link() {
  local path=$1
  local expected_target=$2
  local actual_target

  if [[ ! -L "$path" ]]; then
    error "required VKMS pipeline link is missing: ${path}"
    return 1
  fi
  if ! actual_target=$(readlink -f -- "$path"); then
    error "could not resolve VKMS pipeline link: ${path}"
    return 1
  fi
  if [[ "$actual_target" != "$expected_target" ]]; then
    error "VKMS pipeline link ${path} points to ${actual_target}, not ${expected_target}"
    return 1
  fi
}

validate_topology() {
  local index plane crtc encoder connector

  validate_device_layout || return 1
  cleanup_is_safe || return 1

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    plane="$VKMS_DEVICE_DIR/planes/plane${index}"
    crtc="$VKMS_DEVICE_DIR/crtcs/crtc${index}"
    encoder="$VKMS_DEVICE_DIR/encoders/encoder${index}"
    connector="$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))"

    [[ -d "$plane" && -d "$crtc" && -d "$encoder" && -d "$connector" ]] || {
      error "VKMS pipeline ${index} is incomplete"
      return 1
    }
    attribute_equals "$plane/type" 1 || return 1
    attribute_equals "$crtc/writeback" 0 || return 1
    attribute_is_connection_state "$connector/status" || return 1
    if [[ ! -f "$connector/requested_mode" || -L "$connector/requested_mode" ]]; then
      error "required VKMS requested-mode attribute is missing or unsafe: ${connector}/requested_mode"
      return 1
    fi
    validate_link "$plane/possible_crtcs/crtc${index}" "$crtc" || return 1
    validate_link "$encoder/possible_crtcs/crtc${index}" "$crtc" || return 1
    validate_link "$connector/possible_encoders/encoder${index}" "$encoder" || return 1
  done
}

create_pipeline_items() {
  local index

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    create_configfs_item "$VKMS_DEVICE_DIR/planes/plane${index}" plane || return 1
    write_attribute "$VKMS_DEVICE_DIR/planes/plane${index}/type" 1 || return 1
  done
  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    create_configfs_item "$VKMS_DEVICE_DIR/crtcs/crtc${index}" crtc || return 1
    write_attribute "$VKMS_DEVICE_DIR/crtcs/crtc${index}/writeback" 0 || return 1
  done
  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    create_configfs_item "$VKMS_DEVICE_DIR/encoders/encoder${index}" encoder || return 1
  done
  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    create_configfs_item "$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))" connector || return 1
    write_attribute \
      "$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))/status" \
      "$CONNECTOR_STATUS_DISCONNECTED" || return 1
  done
}

create_pipeline_links() {
  local index plane crtc encoder connector

  for ((index = 0; index < VKMS_OUTPUT_COUNT; ++index)); do
    plane="$VKMS_DEVICE_DIR/planes/plane${index}"
    crtc="$VKMS_DEVICE_DIR/crtcs/crtc${index}"
    encoder="$VKMS_DEVICE_DIR/encoders/encoder${index}"
    connector="$VKMS_DEVICE_DIR/connectors/Virtual-$((index + 1))"

    ln -s -- "$crtc" "$plane/possible_crtcs/crtc${index}" || return 1
    ln -s -- "$crtc" "$encoder/possible_crtcs/crtc${index}" || return 1
    ln -s -- "$encoder" "$connector/possible_encoders/encoder${index}" || return 1
  done
}

build_new_pool() {
  create_configfs_item "$VKMS_DEVICE_DIR" device || return 1
  validate_device_layout || return 1
  create_pipeline_items || return 1
  create_pipeline_links || return 1
  validate_topology || return 1
  write_attribute "$VKMS_DEVICE_DIR/enabled" 1 || return 1
  attribute_equals "$VKMS_DEVICE_DIR/enabled" 1 || return 1
}

create_pool() {
  local enabled_value

  if [[ -d "$VKMS_DEVICE_DIR" ]]; then
    if validate_topology; then
      enabled_value=$(<"$VKMS_DEVICE_DIR/enabled")
      case "$enabled_value" in
        1)
          log "${DRM_BACKEND} display pool is already ready (${VKMS_OUTPUT_COUNT} outputs)"
          return 0
          ;;
        0)
          write_attribute "$VKMS_DEVICE_DIR/enabled" 1 || return 1
          log "enabled existing ${DRM_BACKEND} display pool (${VKMS_OUTPUT_COUNT} outputs)"
          return 0
          ;;
        *)
          error "unexpected enabled state '${enabled_value}'; rebuilding the managed instance"
          ;;
      esac
    else
      log "managed VKMS instance is incomplete; rebuilding it"
    fi
    remove_pool || return 1
  fi

  clear_connector_leases || return 1
  if ! build_new_pool; then
    error "failed to create the private VKMS display pool; rolling back"
    remove_pool || error "rollback was incomplete; inspect ${VKMS_DEVICE_DIR}"
    return 1
  fi

  log "created ${VKMS_OUTPUT_COUNT} dormant private outputs with ${DRM_BACKEND}"
}

select_control_backend() {
  if [[ -L "$VKMS_CONFIGFS_ROOT" || -L "$VKMS_DEVICE_DIR" ]]; then
    error "refusing symbolic-link display backend path"
    return 1
  fi
  if [[ -d "$VKMS_DEVICE_DIR" ]]; then
    return
  fi

  error "managed virtual-display pool is unavailable"
  return 1
}

ensure_lease_root() {
  local owner_uid

  if [[ -L "$LEASE_ROOT" ]]; then
    error "refusing symbolic-link connector lease directory: ${LEASE_ROOT}"
    return 1
  fi
  if [[ ! -e "$LEASE_ROOT" ]]; then
    if ! mkdir -m 0700 -- "$LEASE_ROOT" && [[ ! -d "$LEASE_ROOT" || -L "$LEASE_ROOT" ]]; then
      error "could not create connector lease directory: ${LEASE_ROOT}"
      return 1
    fi
  fi
  if [[ ! -d "$LEASE_ROOT" || -L "$LEASE_ROOT" ]]; then
    error "connector lease path is not a safe directory: ${LEASE_ROOT}"
    return 1
  fi
  if ((FAKE_CONFIGFS == 0)); then
    owner_uid=$(stat -c %u -- "$LEASE_ROOT") || return 1
    if [[ "$owner_uid" != 0 ]]; then
      error "connector lease directory is not owned by root: ${LEASE_ROOT}"
      return 1
    fi
  fi
  if ! chmod 0700 -- "$LEASE_ROOT"; then
    error "could not secure connector lease directory: ${LEASE_ROOT}"
    return 1
  fi
}

read_connector_lease() {
  local connector_name=$1
  local output_variable=$2
  local lease_path="$LEASE_ROOT/${connector_name}.owner"
  local stored_uid=""

  printf -v "$output_variable" '%s' ""
  [[ -e "$lease_path" || -L "$lease_path" ]] || return 0
  if [[ ! -f "$lease_path" || -L "$lease_path" ]]; then
    error "connector lease is not a safe regular file: ${lease_path}"
    return 1
  fi
  stored_uid=$(<"$lease_path")
  if [[ ! "$stored_uid" =~ ^(0|[1-9][0-9]*)$ ]]; then
    error "connector lease contains an invalid uid: ${lease_path}"
    return 1
  fi
  printf -v "$output_variable" '%s' "$stored_uid"
}

write_connector_lease() {
  local connector_name=$1
  local owner_uid=$2
  local lease_path="$LEASE_ROOT/${connector_name}.owner"
  local temporary_path="$LEASE_ROOT/.${connector_name}.owner.${BASHPID}"

  if [[ -L "$lease_path" || (-e "$lease_path" && ! -f "$lease_path") ]]; then
    error "refusing unsafe connector lease path: ${lease_path}"
    return 1
  fi
  if ! printf '%s\n' "$owner_uid" >"$temporary_path" ||
     ! chmod 0600 -- "$temporary_path" ||
     ! mv -fT -- "$temporary_path" "$lease_path"; then
    rm -f -- "$temporary_path"
    error "could not persist connector lease: ${lease_path}"
    return 1
  fi
}

release_connector_lease() {
  local connector_name=$1
  local lease_path="$LEASE_ROOT/${connector_name}.owner"

  [[ -e "$lease_path" || -L "$lease_path" ]] || return 0
  if [[ ! -f "$lease_path" || -L "$lease_path" ]]; then
    error "refusing unsafe connector lease path: ${lease_path}"
    return 1
  fi
  if ! rm -f -- "$lease_path"; then
    error "could not release connector lease: ${lease_path}"
    return 1
  fi
}

clear_connector_leases() {
  local index connector_name

  [[ -n "$LEASE_ROOT" && (-e "$LEASE_ROOT" || -L "$LEASE_ROOT") ]] || return 0
  if [[ ! -d "$LEASE_ROOT" || -L "$LEASE_ROOT" ]]; then
    error "refusing unsafe connector lease directory: ${LEASE_ROOT}"
    return 1
  fi
  for ((index = 1; index <= VKMS_OUTPUT_COUNT; ++index)); do
    connector_name="Virtual-${index}"
    release_connector_lease "$connector_name" || return 1
  done
}

mutate_connector() (
  local action=$1
  local connector_name=$2
  local caller_uid=$3
  local status_path=$4
  local lock_path owner_uid="" current_status lock_fd

  umask 077
  if ! ensure_lease_root; then
    printf 'ERROR connector lease unavailable\n'
    return 1
  fi

  lock_path="$LEASE_ROOT/${connector_name}.lock"
  if [[ -L "$lock_path" || (-e "$lock_path" && ! -f "$lock_path") ]]; then
    error "refusing unsafe connector lock path: ${lock_path}"
    printf 'ERROR connector lease unavailable\n'
    return 1
  fi
  if ! exec {lock_fd}>>"$lock_path" || ! flock -x -w 1 "$lock_fd"; then
    error "could not lock connector lease: ${lock_path}"
    printf 'ERROR connector lease unavailable\n'
    return 1
  fi

  current_status=$(<"$status_path")
  case "$current_status" in
    "$CONNECTOR_STATUS_CONNECTED" | "$CONNECTOR_STATUS_DISCONNECTED")
      ;;
    *)
      printf 'ERROR invalid connector state\n'
      return 1
      ;;
  esac

  if ! read_connector_lease "$connector_name" owner_uid; then
    if [[ "$caller_uid" != 0 ]] || ! release_connector_lease "$connector_name"; then
      printf 'ERROR connector lease unavailable\n'
      return 1
    fi
    owner_uid=""
  fi

  case "$action" in
    connect)
      if [[ "$current_status" == "$CONNECTOR_STATUS_CONNECTED" ]]; then
        if [[ -z "$owner_uid" ]]; then
          if [[ "$caller_uid" != 0 ]] || ! write_connector_lease "$connector_name" 0; then
            printf 'ERROR connector ownership unavailable\n'
            return 1
          fi
        elif [[ "$caller_uid" != 0 && "$caller_uid" != "$owner_uid" ]]; then
          printf 'ERROR connector owned by another uid\n'
          return 1
        fi
        printf 'OK connected %s\n' "$connector_name"
        return 0
      fi

      # A disconnected connector cannot still be in use. Discard bookkeeping
      # left behind by an interrupted disconnect before assigning a new owner.
      release_connector_lease "$connector_name" || {
        printf 'ERROR connector lease unavailable\n'
        return 1
      }
      if ! write_connector_lease "$connector_name" "$caller_uid"; then
        printf 'ERROR connector lease unavailable\n'
        return 1
      fi
      if ! printf '%s\n' "$CONNECTOR_STATUS_CONNECTED" >"$status_path" ||
         [[ $(<"$status_path") != "$CONNECTOR_STATUS_CONNECTED" ]]; then
        release_connector_lease "$connector_name" || true
        printf 'ERROR connector update failed\n'
        return 1
      fi
      printf 'OK connected %s\n' "$connector_name"
      ;;
    disconnect)
      if [[ -n "$owner_uid" && "$caller_uid" != 0 && "$caller_uid" != "$owner_uid" ]]; then
        printf 'ERROR connector owned by another uid\n'
        return 1
      fi
      if [[ -z "$owner_uid" && "$current_status" == "$CONNECTOR_STATUS_CONNECTED" &&
            "$caller_uid" != 0 ]]; then
        printf 'ERROR connector ownership unavailable\n'
        return 1
      fi
      if [[ "$current_status" == "$CONNECTOR_STATUS_CONNECTED" ]] &&
         { ! printf '%s\n' "$CONNECTOR_STATUS_DISCONNECTED" >"$status_path" ||
           [[ $(<"$status_path") != "$CONNECTOR_STATUS_DISCONNECTED" ]]; }; then
        printf 'ERROR connector update failed\n'
        return 1
      fi
      if ! release_connector_lease "$connector_name"; then
        printf 'ERROR connector lease cleanup failed\n'
        return 1
      fi
      printf 'OK disconnected %s\n' "$connector_name"
      ;;
    *)
      printf 'ERROR invalid action\n'
      return 1
      ;;
  esac
)

control_connector() {
  local action=$1
  local connector_name=$2
  local caller_uid=$3
  local connector_dir status_path status_value state

  case "$connector_name" in
    Virtual-1 | Virtual-2 | Virtual-3 | Virtual-4)
      ;;
    *)
      printf 'ERROR invalid connector\n'
      return 1
      ;;
  esac

  if ! configfs_is_mounted || ! select_control_backend; then
    printf 'ERROR display pool unavailable\n'
    return 1
  fi

  connector_dir="$VKMS_DEVICE_DIR/connectors/$connector_name"
  status_path="$connector_dir/status"
  if [[ ! -d "$VKMS_DEVICE_DIR" || -L "$VKMS_DEVICE_DIR" ||
        ! -f "$VKMS_DEVICE_DIR/enabled" || -L "$VKMS_DEVICE_DIR/enabled" ||
        ! -d "$connector_dir" || -L "$connector_dir" ||
        ! -f "$status_path" || -L "$status_path" ]]; then
    printf 'ERROR unsafe connector path\n'
    return 1
  fi
  if [[ $(<"$VKMS_DEVICE_DIR/enabled") != 1 ]]; then
    printf 'ERROR display pool disabled\n'
    return 1
  fi

  case "$action" in
    connect)
      mutate_connector connect "$connector_name" "$caller_uid" "$status_path"
      return
      ;;
    disconnect)
      mutate_connector disconnect "$connector_name" "$caller_uid" "$status_path"
      return
      ;;
    status)
      status_value=$(<"$status_path")
      case "$status_value" in
        "$CONNECTOR_STATUS_CONNECTED") state=connected ;;
        "$CONNECTOR_STATUS_DISCONNECTED") state=disconnected ;;
        *)
          printf 'ERROR invalid connector state\n'
          return 1
          ;;
      esac
      printf 'STATUS %s %s\n' "$state" "$connector_name"
      return 0
      ;;
    *)
      printf 'ERROR invalid action\n'
      return 1
      ;;
  esac

}

control_requested_mode() (
  local connector_name=$1 width=$2 height=$3 refresh=$4 caller_uid=$5
  local connector_dir mode_path status_path lock_path lock_fd owner_uid=""

  if [[ ! "$connector_name" =~ ^Virtual-[1-4]$ ||
        ! "$width" =~ ^[1-9][0-9]{0,3}$ || ! "$height" =~ ^[1-9][0-9]{0,3}$ ||
        ! "$refresh" =~ ^[1-9][0-9]{0,6}$ ]] ||
     ((width < 64 || width > 8192 || height < 64 || height > 8192 ||
       refresh < 1000 || refresh > 1000000)); then
    printf 'ERROR invalid requested mode\n'
    return 1
  fi
  if ! configfs_is_mounted || ! select_control_backend; then
    printf 'ERROR display pool unavailable\n'
    return 1
  fi
  connector_dir="$VKMS_DEVICE_DIR/connectors/$connector_name"
  mode_path="$connector_dir/requested_mode"
  status_path="$connector_dir/status"
  if [[ ! -d "$connector_dir" || -L "$connector_dir" ||
        ! -f "$VKMS_DEVICE_DIR/enabled" || -L "$VKMS_DEVICE_DIR/enabled" ||
        ! -f "$status_path" || -L "$status_path" ||
        ! -f "$mode_path" || -L "$mode_path" ]]; then
    printf 'ERROR requested-mode control unavailable\n'
    return 1
  fi
  if [[ $(<"$VKMS_DEVICE_DIR/enabled") != 1 ]]; then
    printf 'ERROR display pool disabled\n'
    return 1
  fi

  umask 077
  if ! ensure_lease_root; then
    printf 'ERROR connector lease unavailable\n'
    return 1
  fi
  lock_path="$LEASE_ROOT/${connector_name}.lock"
  if [[ -L "$lock_path" || (-e "$lock_path" && ! -f "$lock_path") ]] ||
     ! exec {lock_fd}>>"$lock_path" || ! flock -x -w 1 "$lock_fd"; then
    printf 'ERROR connector lease unavailable\n'
    return 1
  fi
  if ! read_connector_lease "$connector_name" owner_uid ||
     [[ -z "$owner_uid" || "$owner_uid" != "$caller_uid" ]]; then
    printf 'ERROR connector not owned by caller\n'
    return 1
  fi
  if [[ $(<"$status_path") != "$CONNECTOR_STATUS_CONNECTED" ]]; then
    printf 'ERROR connector is disconnected\n'
    return 1
  fi
  # The kernel derives and advertises the 2x companion mode from this atomic
  # base-mode triple. Never disconnect a live connector to change its catalog.
  if ! printf '%s %s %s\n' "$width" "$height" "$refresh" >"$mode_path" ||
     [[ $(<"$mode_path") != "$width $height $refresh" ]]; then
    printf 'ERROR requested mode update failed\n'
    return 1
  fi
  printf 'OK mode %s %s %s %s\n' "$connector_name" "$width" "$height" "$refresh"
)

control_connection() {
  local caller_uid=${1:-}
  local request
  local max_request_bytes=128

  if [[ ! "$caller_uid" =~ ^(0|[1-9][0-9]*)$ ]]; then
    printf 'ERROR peer credentials unavailable\n'
    return 1
  fi

  if ! IFS= read -r -t 2 -n "$max_request_bytes" request; then
    printf 'ERROR malformed request\n'
    return 1
  fi
  if (( ${#request} >= max_request_bytes )); then
    printf 'ERROR request too large\n'
    return 1
  fi

  if [[ "$request" =~ ^mode\ (Virtual-[1-4])\ ([1-9][0-9]{0,3})\ ([1-9][0-9]{0,3})\ ([1-9][0-9]{0,6})$ ]]; then
    control_requested_mode "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" \
      "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}" "$caller_uid"
    return
  fi
  case "$request" in
    "connect Virtual-1" | "connect Virtual-2" | "connect Virtual-3" | "connect Virtual-4" | \
    "disconnect Virtual-1" | "disconnect Virtual-2" | "disconnect Virtual-3" | "disconnect Virtual-4" | \
    "status Virtual-1" | "status Virtual-2" | "status Virtual-3" | "status Virtual-4")
      control_connector "${request%% *}" "${request#* }" "$caller_uid"
      ;;
    *)
      printf 'ERROR malformed request\n'
      return 1
      ;;
  esac
}

status_pool() {
  if [[ ! -d "$VKMS_DEVICE_DIR" ]]; then
    log "private VKMS display pool is not present"
    return 3
  fi
  validate_topology || return 1
  attribute_equals "$VKMS_DEVICE_DIR/enabled" 1 || return 3
  log "${DRM_BACKEND} display pool is ready (${VKMS_OUTPUT_COUNT} outputs)"
}

usage() {
  printf 'Usage: %s {start|stop|restart|status|control}\n' "$PROGRAM_NAME" >&2
}

main() {
  local action=${1:-}

  # Do not accept an environment override for this privileged path. Cleanup is
  # deliberately restricted to one exact configfs instance.
  configure_paths /sys/kernel/config
  configure_lease_paths /run/vibeshine/vkms-leases
  FAKE_CONFIGFS=0

  require_command awk || return 1
  case "$action" in
    start)
      require_root || return 1
      require_command mount || return 1
      require_command modprobe || return 1
      require_command mkdir || return 1
      require_command ln || return 1
      require_command readlink || return 1
      require_command rm || return 1
      require_command unlink || return 1
      require_command rmdir || return 1
      ensure_configfs || return 1
      ensure_display_backend || return 1
      create_pool
      ;;
    stop)
      require_root || return 1
      require_command systemctl || return 1
      require_command unlink || return 1
      require_command rmdir || return 1
      require_command rm || return 1
      if ! configfs_is_mounted; then
        clear_connector_leases || return 1
        log "configfs is not mounted; virtual-display pools are already stopped"
        return 0
      fi
      stop_pool
      ;;
    restart)
      require_root || return 1
      require_command mount || return 1
      require_command modprobe || return 1
      require_command mkdir || return 1
      require_command ln || return 1
      require_command readlink || return 1
      require_command rm || return 1
      require_command unlink || return 1
      require_command rmdir || return 1
      if configfs_is_mounted; then
        remove_pool || return 1
      fi
      ensure_configfs || return 1
      ensure_display_backend || return 1
      create_pool
      ;;
    status)
      if ! configfs_is_mounted; then
        log "configfs is not mounted; virtual-display pool is not present"
        return 3
      fi
      status_pool
      ;;
    control)
      require_root || return 1
      require_command awk || return 1
      require_command chmod || return 1
      require_command flock || return 1
      require_command mkdir || return 1
      require_command mv || return 1
      require_command rm || return 1
      require_command stat || return 1
      control_connection "${2:-}"
      ;;
    *)
      usage
      return 2
      ;;
  esac
}

if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
  main "$@"
fi
