#!/bin/bash

# transset in a bash script
# Copyright (c) 2011-2012, Christopher Jeffrey

# Usage:
# by window id
#   settrans -w "$WINDOWID" -o 75
# by name
#   settrans -n "urxvt" -o 75
# by current window
#   settrans -c -o 75
# by selection
#   settrans -s -o 75
# increment current window 5%
#   settrans -c -o +5

if test -z "$(which xprop)" -o -z "$(which xwininfo)"; then
  echo "Please install x11-utils/xorg-xprop/xorg-xwininfo." >& 2
  exit 1
fi

window=
opacity=
cur=
root=
parent=
active=
i=

while getopts "scn:w:o:" option; do
  case "$option" in
    s) window="" ;;
    c)
      active=$(xprop -root -notype "_NET_ACTIVE_WINDOW" \
        | sed 's/^.*\(0x\S*\).*$/\1/')
      window="-id $active"
    ;;
    n) window="-name $OPTARG" ;;
    w) window="-id $OPTARG" ;;
    o) opacity="$OPTARG" ;;
  esac
done

root=$(xwininfo -all -root \
  | grep "Root window id" \
  | sed 's/^.*\(0x\S*\).*$/\1/')

parent=$window
i=0
while true; do
  parent=$(xwininfo -all $parent \
    | grep Parent \
    | sed 's/^.*\(0x\S*\).*$/\1/')

  if test "$parent" = "$root"; then
    break
  fi

  parent="-id $parent"
  window=$parent

  i=$((i+1))
  if test $i -ge 1000; then
    echo "An error occurred while traversing up the window tree." >& 2
    echo "Please report this to https://github.com/chjj/compton/issues." >& 2
    echo "Please mention your WM and versions of xwininfo/xprop." >& 2
    exit 1
  fi
done

inc=$(echo "$opacity" | sed 's/^\(+\|-\).*$\|^.*$/\1/')
if test -n "$inc"; then
  cur=$(xprop $window -notype "_NET_WM_WINDOW_OPACITY" \
    | sed 's/^.*\b\([0-9]\+\).*$\|^.*$/\1/')
  test -z "$cur" && cur=$((0xffffffff))
  cur=$((cur*100/0xffffffff))
  opacity=$(echo "$opacity" | sed 's/\(\+\|\-\)//')
  if test "$inc" = "+"; then
    opacity=$((cur+opacity))
  else
    opacity=$((cur-opacity))
  fi
fi

if test -n "$opacity" -a -n "$window"; then
  test $opacity -lt 0 && opacity=0
  test $opacity -gt 100 && opacity=100
  opacity=$((opacity*0xffffffff/100))
  xprop $window -f _NET_WM_WINDOW_OPACITY 32c \
    -set _NET_WM_WINDOW_OPACITY "$opacity"
fi