#!/usr/bin/env bash
set -euo pipefail

# Map logical degrees -> wlr-randr transform for this device
# Device reality: 0° logical == 270 transform (normal handheld portrait)
map_degree() {
  local d=${1:-}
  case "$d" in
    0)   echo 270;;     # logical 0 -> transform 270
    90)  echo normal;;  # logical 90 -> transform normal
    180) echo 90;;      # logical 180 -> transform 90
    270) echo 180;;     # logical 270 -> transform 180
    *)   echo "";;
  esac
}

# Pick the DSI output name dynamically (DSI-1 or DSI-2)
detect_output() {
  local out
  out=$(wlr-randr | awk '/^DSI-[12]/{print $1; exit}') || true
  if [[ -z "$out" ]]; then
    echo "Error: No DSI output found (need Wayland + wlr-randr)" >&2
    exit 1
  fi
  echo "$out"
}

# Read current transform from wlr-randr line like:
#   DSI-1 … transform: 270
current_transform() {
  local out="$1"
  wlr-randr | awk -v o="$out" '$1==o {for(i=1;i<=NF;i++){if($i=="transform:"){print $(i+1); exit}}}'
}

# Compute next transform in 90° steps using the logical mapping
next_transform() {
  local cur="$1"
  # reverse-map current physical transform to logical degrees
  local logical
  case "$cur" in
    270) logical=0;;
    normal) logical=90;;
    90) logical=180;;
    180) logical=270;;
    *) logical=90;; # fallback
  esac
  local next=$(( (logical + 90) % 360 ))
  map_degree "$next"
}

main() {
  local out; out=$(detect_output)
  local arg=${1:-}
  local transform

  if [[ -z "$arg" ]]; then
    local cur; cur=$(current_transform "$out")
    transform=$(next_transform "$cur")
  else
    # normalize arg (allow 0/90/180/270)
    case "$arg" in
      0|90|180|270) transform=$(map_degree "$arg");;
      *) echo "Usage: ucon-rotate [0|90|180|270]" >&2; exit 2;;
    esac
  fi

  if [[ -z "$transform" ]]; then
    echo "Error: could not resolve transform" >&2
    exit 1
  fi

  exec wlr-randr --output "$out" --transform "$transform"
}

main "$@"
