#!/bin/bash

# omarchy:summary=Manage the webcam relay and image tuning for this laptop
# omarchy:subcommand=on [--force] — Start the userland camera relay with this laptop's tuning
# omarchy:subcommand=off — Stop and remove the userland camera relay
# omarchy:subcommand=status — Show whether camera tuning is active and its current values
# omarchy:subcommand=match — Print the camera tuning that matches this laptop, if any
# omarchy:subcommand=set [key=value ...] — Override tuning values in ~/.config/omarchy/camera.conf and apply
# omarchy:subcommand=reset — Remove user overrides in ~/.config/omarchy/camera.conf and restore defaults
# omarchy:group=camera
# omarchy:examples=omarchy camera tuning status | omarchy camera tuning set gamma=1.5 contrast=1.05 saturation=1.4 | omarchy camera tuning reset

set -uo pipefail

script_dir="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
tunings_dir="$OMARCHY_PATH/default/camera/tunings"
config_home="${XDG_CONFIG_HOME:-$HOME/.config}"

env_file="$config_home/omarchy/camera-relay.env"
override_file="$config_home/omarchy/camera.conf"
user_ipa_dir="$config_home/omarchy/camera/ipa"

relay_unit_name=omarchy-camera-relay.service
guard_unit_name=omarchy-camera-guard.service
relay_unit="$config_home/systemd/user/$relay_unit_name"
guard_unit="$config_home/systemd/user/$guard_unit_name"
relay_unit_source="$OMARCHY_PATH/default/systemd/user/$relay_unit_name"
guard_unit_source="$OMARCHY_PATH/default/systemd/user/$guard_unit_name"

relay_bin="$script_dir/omarchy-camera-relay"
guard_bin="$script_dir/omarchy-camera-guard"

action="${1:-status}"
shift || true

dt_matches() {
  local want
  for want in "$@"; do
    omarchy-hw-match-device-tree "$want" 2>/dev/null && return 0
  done
  return 1
}

dmi_matches() {
  local want
  for want in "$@"; do
    omarchy-hw-match "$want" 2>/dev/null && return 0
  done
  return 1
}

tuning_match() {
  local dir
  [[ -d $tunings_dir ]] || return 1
  for dir in "$tunings_dir"/*/; do
    [[ -r $dir/tuning.conf ]] || continue

    unset match_dt match_dmi match_command camera_name
    # shellcheck disable=SC1090
    source "$dir/tuning.conf"

    if [[ -n ${match_command:-} ]]; then
      "$match_command" 2>/dev/null || continue
    elif [[ -n ${match_dt:-} ]]; then
      dt_matches "${match_dt[@]}" || continue
    elif [[ -n ${match_dmi:-} ]]; then
      dmi_matches "${match_dmi[@]}" || continue
    else
      continue
    fi

    [[ -n ${camera_name:-} ]] || continue
    printf '%s\n' "${dir%/}"
    return 0
  done
  return 1
}

valid_override() {
  local key="$1" val="$2"
  case "$key" in
    gamma|contrast|saturation)
      [[ $val =~ ^[0-9]+(\.[0-9]+)?$ ]] ;;
    brightness|warmth|tint)
      [[ $val =~ ^-?[0-9]+(\.[0-9]+)?$ ]] ;;
    width|height)
      [[ $val =~ ^[1-9][0-9]{1,4}$ ]] ;;
    framerate)
      [[ $val =~ ^[1-9][0-9]*/[1-9][0-9]*$ ]] ;;
    format)
      [[ $val =~ ^[A-Z0-9_]+$ ]] ;;
    card_label)
      [[ -n $val && $val != *$'\n'* && $val != *\"* && $val != *\'* ]] ;;
    *)
      return 1 ;;
  esac
}

load_overrides() {
  local file="$1" line key val
  [[ -r $file ]] || return 0
  while IFS= read -r line || [[ -n $line ]]; do
    line="${line%%#*}"
    line="${line#"${line%%[![:space:]]*}"}"
    line="${line%"${line##*[![:space:]]}"}"
    [[ -z $line ]] && continue
    [[ $line == *=* ]] || continue
    key="${line%%=*}"
    val="${line#*=}"
    key="${key%"${key##*[![:space:]]}"}"
    val="${val#"${val%%[![:space:]]*}"}"
    val="${val#\"}"
    val="${val%\"}"
    val="${val#\'}"
    val="${val%\'}"
    if valid_override "$key" "$val"; then
      printf -v "$key" '%s' "$val"
    else
      echo "omarchy-camera-tuning: ignoring invalid override '$key=$val' in $file" >&2
    fi
  done <"$file"
}

pipewire_source_present() {
  local label="$1"
  wpctl status 2>/dev/null | awk '/Video/,/Settings/' | grep -Fq "$label (V4L2)"
}

render_env() {
  local selected="$1" out="$2" shipped_ipa="" base_gamma=""
  unset description camera_dt_node camera_name card_label width height format framerate gamma contrast saturation brightness warmth tint ipa_dir
  # shellcheck disable=SC1090
  source "$selected/tuning.conf"
  base_gamma="${gamma:-1.5}"
  load_overrides "$override_file"
  [[ -n ${ipa_dir:-} && -d $selected/$ipa_dir ]] && shipped_ipa="$selected/$ipa_dir"

  cat >"$out" <<EOF
# Generated by omarchy-camera-tuning. Do not edit directly;
# put persistent overrides in $override_file or run:
#   omarchy camera tuning set gamma=1.5 contrast=1.05 saturation=1.4
RELAY_SCHEMA=2
TUNING_NAME=$(printf '%q' "$(basename "$selected")")
DESCRIPTION=$(printf '%q' "${description:-}")
CAMERA_DT_NODE=$(printf '%q' "${camera_dt_node:-}")
CAMERA_NAME=$(printf '%q' "$camera_name")
CARD_LABEL=$(printf '%q' "${card_label:-Front Camera}")
WIDTH=$(printf '%q' "${width:-1920}")
HEIGHT=$(printf '%q' "${height:-1080}")
FORMAT=$(printf '%q' "${format:-NV12}")
FRAMERATE=$(printf '%q' "${framerate:-30/1}")
BASE_GAMMA=$(printf '%q' "$base_gamma")
GAMMA=$(printf '%q' "${gamma:-}")
CONTRAST=$(printf '%q' "${contrast:-}")
SATURATION=$(printf '%q' "${saturation:-}")
BRIGHTNESS=$(printf '%q' "${brightness:-0}")
WARMTH=$(printf '%q' "${warmth:-0}")
TINT=$(printf '%q' "${tint:-0}")
SHIPPED_IPA_DIR=$(printf '%q' "$shipped_ipa")
EOF
}

env_structural_part() {
  grep -Ev '^(GAMMA|CONTRAST|SATURATION|BRIGHTNESS|WARMTH|TINT)=' "$1"
}

live_apply_socket() {
  local sock="${OMARCHY_CAMERA_RELAY_SOCKET:-${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/omarchy-camera-relay.sock}"
  [[ -S $sock ]] || return 1
  python3 - "$sock" "${1:-}" "${2:-}" "${3:-}" "${4:-}" "${5:-}" "${6:-}" <<'PY'
import socket, sys
sock_path, gamma, contrast, saturation, brightness, warmth, tint = sys.argv[1:8]
parts = []
if gamma: parts.append(f"gamma={gamma}")
if contrast: parts.append(f"contrast={contrast}")
if saturation: parts.append(f"saturation={saturation}")
if brightness: parts.append(f"brightness={brightness}")
if warmth: parts.append(f"warmth={warmth}")
if tint: parts.append(f"tint={tint}")
if not parts:
    raise SystemExit(0)
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
    s.sendto(" ".join(parts).encode("utf-8"), sock_path)
finally:
    s.close()
PY
}

case "$action" in
  match)
    tuning_match
    ;;

  status)
    if [[ -r $env_file ]]; then
      echo "Installed:     yes ($env_file)"
      # shellcheck disable=SC1090
      source "$env_file"
      echo "Tuning:        ${DESCRIPTION:-${TUNING_NAME:-?}}"
      echo "Active values: brightness=${BRIGHTNESS:-0} gamma=${GAMMA:-default} contrast=${CONTRAST:-default} saturation=${SATURATION:-default} warmth=${WARMTH:-0} tint=${TINT:-0} (${WIDTH}x${HEIGHT} ${FORMAT} ${FRAMERATE})"
    else
      echo "Installed:     no"
    fi
    if [[ -r $override_file ]]; then
      echo "Overrides:     $override_file"
    else
      echo "Overrides:     none (edit $override_file or run: omarchy camera tuning set ...)"
    fi
    if [[ -d $user_ipa_dir ]]; then
      echo "User IPA dir:  $user_ipa_dir"
    fi
    relay_state="$(systemctl --user is-active "$relay_unit_name" 2>/dev/null)"
    relay_enabled="$(systemctl --user is-enabled "$relay_unit_name" 2>/dev/null)"
    guard_state="$(systemctl --user is-active "$guard_unit_name" 2>/dev/null)"
    echo "Relay service: ${relay_state:-inactive} (${relay_enabled:-disabled})"
    echo "Guard service: ${guard_state:-inactive}"
    if dir="$(tuning_match)"; then
      unset description
      # shellcheck disable=SC1090
      source "$dir/tuning.conf"
      echo "Matches:       ${description:-?} ($(basename "$dir"))"
    else
      echo "Matches:       nothing ships for this laptop"
    fi
    ;;

  off)
    if [[ ! -r $env_file && ! -r $relay_unit && ! -r $guard_unit ]]; then
      echo "No camera tuning installed."
      exit 0
    fi
    systemctl --user disable --now "$guard_unit_name" "$relay_unit_name" >/dev/null 2>&1 || true
    rm -f "$env_file" "$relay_unit" "$guard_unit"
    systemctl --user daemon-reload >/dev/null 2>&1 || true
    echo "Camera tuning removed."
    ;;

  set)
    if (($# == 0)); then
      echo "Usage: omarchy-camera-tuning set key=value [key=value ...]" >&2
      echo "Allowed keys: brightness, gamma, contrast, saturation, warmth, tint, width, height, framerate, format, card_label" >&2
      exit 2
    fi

    declare -A updates=()
    for arg in "$@"; do
      if [[ $arg != *=* ]]; then
        echo "Invalid argument '$arg' (expected key=value)" >&2
        exit 2
      fi
      key="${arg%%=*}"
      val="${arg#*=}"
      if ! valid_override "$key" "$val"; then
        echo "Invalid override '$key=$val'" >&2
        exit 2
      fi
      updates["$key"]="$val"
    done

    mkdir -p "$(dirname "$override_file")"
    tmp="$(mktemp)"
    trap 'rm -f "$tmp"' EXIT
    declare -A written=()
    if [[ -r $override_file ]]; then
      while IFS= read -r line || [[ -n $line ]]; do
        trimmed="${line#"${line%%[![:space:]]*}"}"
        if [[ $trimmed != \#* && $trimmed == *=* ]]; then
          existing_key="${trimmed%%=*}"
          existing_key="${existing_key%"${existing_key##*[![:space:]]}"}"
          if [[ -v updates[$existing_key] ]]; then
            printf '%s=%s\n' "$existing_key" "${updates[$existing_key]}" >>"$tmp"
            written["$existing_key"]=1
            continue
          fi
        fi
        printf '%s\n' "$line" >>"$tmp"
      done <"$override_file"
    fi
    for key in "${!updates[@]}"; do
      [[ -v written[$key] ]] && continue
      printf '%s=%s\n' "$key" "${updates[$key]}" >>"$tmp"
    done
    install -Dm644 "$tmp" "$override_file"
    rm -f "$tmp"
    trap - EXIT

    exec "$0" on --live
    ;;

  reset)
    rm -f "$override_file"
    echo "Cleared user overrides ($override_file)."
    exec "$0" on --live
    ;;

  on)
    force=0
    live=0
    [[ ${1:-} == "--force" ]] && force=1
    [[ ${1:-} == "--live" ]] && live=1

    selected="$(tuning_match)" || {
      echo "No camera tuning matches this laptop."
      exit 0
    }

    unset description camera_dt_node card_label brightness warmth tint
    # shellcheck disable=SC1090
    source "$selected/tuning.conf"
    load_overrides "$override_file"

    if [[ -n ${camera_dt_node:-} && ! -e $camera_dt_node ]]; then
      echo "Camera device-tree node $camera_dt_node is absent on this boot; skipping."
      exit 0
    fi

    rendered_env="$(mktemp)"
    rendered_relay="$(mktemp)"
    rendered_guard="$(mktemp)"
    trap 'rm -f "$rendered_env" "$rendered_relay" "$rendered_guard"' EXIT

    render_env "$selected" "$rendered_env"
    install -Dm644 "$relay_unit_source" "$rendered_relay"
    sed -i -e "s|@RELAY_BIN@|$relay_bin|g" "$rendered_relay"
    install -Dm644 "$guard_unit_source" "$rendered_guard"
    sed -i -e "s|@GUARD_BIN@|$guard_bin|g" "$rendered_guard"

    if ((!force)) && [[ -r $env_file ]] && cmp -s "$rendered_env" "$env_file" &&
      [[ -r $relay_unit ]] && cmp -s "$rendered_relay" "$relay_unit" &&
      [[ -r $guard_unit ]] && cmp -s "$rendered_guard" "$guard_unit" &&
      systemctl --user is-active --quiet "$relay_unit_name" 2>/dev/null &&
      systemctl --user is-enabled --quiet "$relay_unit_name" 2>/dev/null; then
      echo "Camera tuning already current: ${description:-$(basename "$selected")}"
      exit 0
    fi

    # Hot-apply live gamma/contrast/saturation changes over the relay control
    # socket without restarting the service or interrupting active streams.
    if ((live)) && [[ -r $env_file ]] &&
      [[ -r $relay_unit ]] && cmp -s "$rendered_relay" "$relay_unit" &&
      [[ -r $guard_unit ]] && cmp -s "$rendered_guard" "$guard_unit" &&
      diff -q <(env_structural_part "$rendered_env") <(env_structural_part "$env_file") >/dev/null 2>&1 &&
      systemctl --user is-active --quiet "$relay_unit_name" 2>/dev/null &&
      live_apply_socket "${gamma:-}" "${contrast:-}" "${saturation:-}" "${brightness:-0}" "${warmth:-0}" "${tint:-0}" 2>/dev/null; then
      install -Dm644 "$rendered_env" "$env_file"
      echo "Applied camera tuning live: ${description:-$(basename "$selected")} (brightness=${brightness:-0} gamma=${gamma:-default} contrast=${contrast:-default} saturation=${saturation:-default} warmth=${warmth:-0} tint=${tint:-0})"
      exit 0
    fi

    install -Dm644 "$rendered_env" "$env_file"
    install -Dm644 "$rendered_relay" "$relay_unit"
    install -Dm644 "$rendered_guard" "$guard_unit"

    systemctl --user daemon-reload &&
      systemctl --user enable "$relay_unit_name" "$guard_unit_name" &&
      { systemctl --user reset-failed "$relay_unit_name" >/dev/null 2>&1 || true; } &&
      systemctl --user restart "$relay_unit_name" || {
      echo "Couldn't start $relay_unit_name" >&2
      exit 1
    }
    # Guard stands down with ExecCondition exit 1 on libcamera >= 0.8.0, so a
    # skipped restart is expected and not an error.
    systemctl --user restart "$guard_unit_name" >/dev/null 2>&1 || true

    # If WirePlumber was already running before the relay opened the v4l2loopback
    # output side, it may still hold the initial output-only view. Restart it once
    # so Front Camera (V4L2) appears as a PipeWire Video/Source.
    target_label="${card_label:-Front Camera}"
    if systemctl --user is-active --quiet wireplumber.service 2>/dev/null &&
      ! pipewire_source_present "$target_label"; then
      systemctl --user try-restart wireplumber.service >/dev/null 2>&1 || true
      for _ in {1..20}; do
        pipewire_source_present "$target_label" && break
        sleep 0.25
      done
    fi

    echo "Applied camera tuning: ${description:-$(basename "$selected")} (gamma=${gamma:-default} contrast=${contrast:-default} saturation=${saturation:-default})"
    ;;

  *)
    echo "Usage: omarchy-camera-tuning <on|off|status|match|set|reset> [args]" >&2
    exit 2
    ;;
esac
