#!/usr/bin/env bash
# Add exact client modes to the existing root-owned connector lease protocol.
# Both scripts are verified immutable siblings in the installed /opt bundle.
set -uo pipefail

broker_directory=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) || exit 1
source "$broker_directory/vibeshine-vkms"

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
  # One configfs write replaces all three fields under the kernel's lock and
  # refreshes only the mode catalog. Never disconnect a live connector here.
  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:-} request
  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 128 request || ((${#request} >= 128)); then
    printf 'ERROR malformed request\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
}

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