#!/usr/bin/env bash
# Draw the sway background from the regolith.wallpaper.* resources, the way
# the X11 session draws them through org.gnome.desktop.background:
#
#   - regolith.wallpaper.file: an image, or a GNOME wallpaper XML file;
#   - regolith.wallpaper.color.primary, .color.secondary and
#     .color.shading.type (solid, vertical or horizontal): the background when
#     there is no image. Colours can be anything GNOME accepts: #RGB, #RRGGBB,
#     #RRRGGGBBB, #RRRRGGGGBBBB, rgb(), rgba() or a colour name;
#   - regolith.wallpaper.mode (a swaybg mode), or else
#     regolith.wallpaper.options (a GNOME picture-options value).
#
# When neither the file nor the primary colour has a value, the background is
# left alone, as in X11.

set -uo pipefail

RGB_TXT=${REGOLITH_SWAYBG_RGB_TXT:-/usr/share/X11/rgb.txt}
GRADIENT_DIR=${XDG_RUNTIME_DIR:-/tmp}/regolith-swaybg

warn() {
  echo "regolith-set-swaybg: $*" >&2
}

resource() {
  trawlcat "$1" ""
}

# to_hex <colour>: print the colour as #rrggbb, or fail
to_hex() {
  local c=$1 n r g b
  c=${c#"${c%%[![:space:]]*}"}
  c=${c%"${c##*[![:space:]]}"}

  if [[ $c =~ ^#([[:xdigit:]]+)$ ]]; then
    local hex=${BASH_REMATCH[1],,}
    n=$(( ${#hex} / 3 ))
    if (( ${#hex} % 3 != 0 || n < 1 || n > 4 )); then
      return 1
    fi
    r=${hex:0:n}; g=${hex:n:n}; b=${hex:2*n:n}
    if (( n == 1 )); then
      printf '#%02x%02x%02x\n' $((16#$r * 17)) $((16#$g * 17)) $((16#$b * 17))
    else
      printf '#%s%s%s\n' "${r:0:2}" "${g:0:2}" "${b:0:2}"
    fi
    return 0
  fi

  local num='[[:space:]]*([0-9]+(\.[0-9]+)?%?)[[:space:]]*'
  if [[ ${c,,} =~ ^rgba?\($num,$num,$num(,[^\)]*)?\)$ ]]; then
    local out=() v
    for v in "${BASH_REMATCH[1]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[5]}"; do
      if [[ $v == *% ]]; then
        v=$(awk -v p="${v%\%}" 'BEGIN { v = p * 255 / 100; if (v > 255) v = 255; printf "%d", v + 0.5 }')
      else
        v=${v%%.*}
      fi
      (( v > 255 )) && v=255
      out+=("$v")
    done
    printf '#%02x%02x%02x\n' "${out[@]}"
    return 0
  fi

  # Colour names: GNOME (Pango) uses the X11 colour names, without regard to
  # case or spaces
  local name=${c,,}
  name=${name//[[:space:]]/}
  [[ -n $name && -r $RGB_TXT ]] || return 1
  awk -v want="$name" '
    /^[[:space:]]*!/ { next }
    NF >= 4 {
      n = ""
      for (i = 4; i <= NF; i++) n = n $i
      if (tolower(n) == want) { printf "#%02x%02x%02x\n", $1, $2, $3; found = 1; exit }
    }
    END { exit !found }' "$RGB_TXT"
}

# gradient <file> <width> <height> <vertical|horizontal> <#rrggbb> <#rrggbb>:
# write a PNG going from the first colour (top or left) to the second, as
# GNOME draws color-shading-type
gradient() {
  python3 - "$@" <<'EOF'
import os, struct, sys, zlib

path, width, height, kind, first, second = sys.argv[1:]
width, height = max(1, int(width)), max(1, int(height))
a = [int(first[i:i + 2], 16) for i in (1, 3, 5)]
b = [int(second[i:i + 2], 16) for i in (1, 3, 5)]

def colour(i, n):
    t = i / (n - 1) if n > 1 else 0
    return bytes(round(x + (y - x) * t) for x, y in zip(a, b))

z = zlib.compressobj(6)
data = []
if kind == "vertical":
    for y in range(height):
        data.append(z.compress(b"\0" + colour(y, height) * width))
else:
    row = b"\0" + b"".join(colour(x, width) for x in range(width))
    for _ in range(height):
        data.append(z.compress(row))
data.append(z.flush())

def chunk(tag, body):
    return struct.pack(">I", len(body)) + tag + body + struct.pack(">I", zlib.crc32(tag + body))

tmp = path + ".tmp"
with open(tmp, "wb") as f:
    f.write(b"\x89PNG\r\n\x1a\n")
    f.write(chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)))
    f.write(chunk(b"IDAT", b"".join(data)))
    f.write(chunk(b"IEND", b""))
os.replace(tmp, path)
EOF
}

# draw_gradient <vertical|horizontal> <#rrggbb> <#rrggbb>: give each active
# output a gradient image of its own size; fail if there is no output
draw_gradient() {
  local dir=$GRADIENT_DIR name width height file
  local cmds=() keep=()
  mkdir -p "$dir" || return 1
  while read -r name width height; do
    file="$dir/gradient-$1-${2#\#}-${3#\#}-${width}x$height.png"
    if [[ ! -f $file ]]; then
      gradient "$file" "$width" "$height" "$1" "$2" "$3" || continue
    fi
    if (( ${#cmds[@]} == 0 )); then
      # Outputs that are connected later get the first output's image
      cmds+=("output * background $file fill $2")
    fi
    cmds+=("output \"$name\" background $file fill $2")
    keep+=("$file")
  done < <(swaymsg -t get_outputs | jq -r '.[] | select(.active) |
    "\(.name) \(.rect.width * (.scale // 1) | round) \(.rect.height * (.scale // 1) | round)"')
  (( ${#cmds[@]} > 0 )) || return 1

  swaymsg "$(IFS=';'; echo "${cmds[*]}")" > /dev/null || return 1
  # Drop the images of earlier colours and output sizes
  local old kept
  for old in "$dir"/gradient-*.png; do
    for kept in "${keep[@]}"; do
      [[ $old == "$kept" ]] && continue 2
    done
    rm -f "$old"
  done
}

wallpaper=$(resource regolith.wallpaper.file)
options=$(resource regolith.wallpaper.options)
mode=$(resource regolith.wallpaper.mode)
primary=$(resource regolith.wallpaper.color.primary)
secondary=$(resource regolith.wallpaper.color.secondary)
shading=$(resource regolith.wallpaper.color.shading.type)

if [[ -z $wallpaper && -z $primary ]]; then
  # Nothing is set: the background is the user's to manage
  exit 0
fi

if [[ -z $mode ]]; then
  case $options in
    wallpaper) mode=tile ;;
    centered) mode=center ;;
    scaled) mode=fit ;;
    stretched) mode=stretch ;;
    none) mode=fill; wallpaper= ;;
    *) mode=fill ;;
  esac
fi

color="#000000"
if [[ -n $primary ]] && ! color=$(to_hex "$primary"); then
  warn "regolith.wallpaper.color.primary: not a colour: '$primary'"
  color="#000000"
fi

if [[ -n $wallpaper ]]; then
  wallpaper=${wallpaper/#\~/$HOME}
  if [[ ! -f $wallpaper ]]; then
    warn "regolith.wallpaper.file: no such file: '$wallpaper'"
    wallpaper=
  fi
fi

if [[ -z $wallpaper ]]; then
  if [[ -n $secondary && ( $shading == vertical || $shading == horizontal ) ]]; then
    if second=$(to_hex "$secondary"); then
      draw_gradient "$shading" "$color" "$second" && exit 0
    else
      warn "regolith.wallpaper.color.secondary: not a colour: '$secondary'"
    fi
  fi
  rm -f "$GRADIENT_DIR"/gradient-*.png
  exec swaymsg output "*" background "$color" solid_color
fi

rm -f "$GRADIENT_DIR"/gradient-*.png
is_xml=false
if file -b "$wallpaper" | grep -q text && xmllint --noout "$wallpaper" 2> /dev/null; then
  is_xml=true
fi

if [[ $is_xml == true ]]; then
  image_path=$(xmllint "$wallpaper" --xpath "string(*//size[last()]/text())")
  swaymsg output "*" background "$image_path" "$mode" "$color"
  while read -r name width height; do
    wallpaper_file=$(xmllint "$wallpaper" --xpath "string(*//size[@width=$width][@height=$height]/text())")

    if [[ -n "$wallpaper_file" ]]; then
      swaymsg output "\"$name\"" background "$wallpaper_file" "$mode" "$color"
    fi
  done < <(swaymsg -t get_outputs | jq -r '.[] | select(.active) | "\(.name) \(.current_mode.width) \(.current_mode.height)"')
else
  exec swaymsg output "*" background "$wallpaper" "$mode" "$color"
fi
