#!/bin/sh

TARGET_DISPLAYS=

set -e

if [ ! -x "$(which wmctrl 2>/dev/null)" ]; then
   echo "You should install the \"wmctrl\" package" 1>&2
   echo "Type: sudo apt-get install wmctrl" 1>&2
   exit 1
fi

# вычисляем доступную область рабочего стола
read DX DY DW DH <<__EOL__
   $(wmctrl -d |
   sed -n 's/^[0-9]\+\s*\*.*WA:\s*\([0-9]\+\),\([0-9]\+\)\s*\([0-9]\+\)x\([0-9]\+\).*/\1 \2 \3 \4/p')
__EOL__

if [ -z "$DX" -o -z "$DY" -o -z "$DW" -o -z "$DH" ]; then
   echo "ERROR 1: Couldn't determine the desktop workarea geometry." >&2
   echo >&2
   echo "This wrapper work only on Xorg." >&2
   echo "On Wayland-based host use this wrapper into \"Gnome on Xorg\" session" >&2
   echo "or use tile window manager SWayWM" >&2
   exit 1
fi
DW_HALF=$(($DW / 2))

case "$1" in
'-h' | '--help')
   echo "Usage: ${0##*/} [left|right|both]" 1>&2
   exit 1
   ;;
'right')
   TARGET_DISPLAYS="right"
   shift
   ;;
'left')
   TARGET_DISPLAYS="left"
   shift
   ;;
*)
   TARGET_DISPLAYS="right left"
   break
   ;;
esac

get_win_id() {
   [ -z "$1" ] && exit 2
   local target_display tryes count win_id
   win_id=''
   target_display="$1"
   tryes=${2:-1}
   count=0
   while [ $count -lt $tryes ]; do
      win_id=$(wmctrl -l | awk "/\[$target_display]*:[0-9]+\] AVReg/ {print \$1}")
      [ -z "$win_id" ] && sleep 1 || break
      count=$(($count + 1))
   done
   echo $win_id
}

for TARGET_DISPLAY in $TARGET_DISPLAYS; do
   if [ "$TARGET_DISPLAY" = 'right' ]; then
      dx=$(($DX + $DW_HALF))
   else
      dx=$DX
   fi
   AVREGMON_GEO="--geo=${DW_HALF}x${DX} --no-winframe -q"

   WIN_ID=$(get_win_id ${TARGET_DISPLAY})
   if [ -z "$WIN_ID" ]; then
      echo "\"avreg-mon --display=${TARGET_DISPLAY}\" not running, try to exec ..."
      avreg-mon --display=${TARGET_DISPLAY} ${AVREGMON_GEO} $@ >/dev/null &
      WIN_ID=$(get_win_id ${TARGET_DISPLAY} 3)
      if [ -z "$WIN_ID" ]; then
         echo "ERROR 2: exec \"avreg-mon --display=${TARGET_DISPLAY} ${AVREGMON_GEO} $@\" failed" 1>&2
         exit 3
      fi
   fi

   wmctrl -i -r $WIN_ID -e "0,${dx},${DY},-1,-1"
   wmctrl -i -r $WIN_ID -b "add,above,sticky"
done
