#!/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 180;;     # logical 90 -> transform 180 (fixed)
    180) echo 90;;      # logical 180 -> transform 90
    270) echo normal;;  # logical 270 -> transform normal (fixed)
    *)   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"
  # Query the single output and print the value on the "Transform:" line (field 2)
  # Use only POSIX-friendly awk features for compatibility
  local val
  val=$(wlr-randr --output "$out" | awk 'tolower($1)=="transform:" {print $2; exit}') || true
  if [[ -z "$val" ]]; then
    # Fallback: parse from the summary line for that output
    val=$(wlr-randr | awk -v o="$out" 'tolower($1)==tolower(o) {for(i=1;i<=NF;i++){if(tolower($i)=="transform:"){print $(i+1); exit}}}') || true
  fi
  echo "$val"
}

# Compute transform after rotating by a delta (in logical degrees),
# using the device-specific logical<->transform mapping.
compute_transform_with_delta() {
  local cur="$1"
  local delta="$2"  # can be negative (e.g., -90)
  # Reverse-map current PHYSICAL state: transform -> logical degrees
  local logical
  case "$cur" in
    270) logical=0;;
    180) logical=90;;
    90)  logical=180;;
    normal|0) logical=270;;
    *) logical=0;;
  esac
  # Normalize wrap-around for negative values safely
  local next=$(( ( (logical + delta) % 360 + 360 ) % 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=$(compute_transform_with_delta "$cur" 90)
  else
    # normalize arg (allow 0/90/180/270)
    case "$arg" in
      right)
        local cur; cur=$(current_transform "$out")
        transform=$(compute_transform_with_delta "$cur" 90)
        ;;
      left)
        local cur; cur=$(current_transform "$out")
        transform=$(compute_transform_with_delta "$cur" -90)
        ;;
      0|90|180|270) transform=$(map_degree "$arg");;
      *) echo "Usage: uconsole-rotate [right|left|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 "$@"
