#!/bin/bash
#
# Copyright (c) 2017 Yandex LLC. All rights reserved.

DCONF_BIN="dconf"
XMLLINT_BIN="xmllint"
COMPIZ_CONFIG="/usr/share/compiz/composite.xml"
COMPIZ_XPATH="/compiz/plugin/options/option[@name='unredirect_match']/default/\
text()"
COMPIZ_PROFILES="/org/compiz/profiles/"
UNREDIRECT_MATCH_KEY="plugins/composite/unredirect-match"
YANDEX_WINDOW_CLASS="!(class=yandex-browser)"
YANDEX_BETA_WINDOW_CLASS="!(class=yandex-browser-beta)"
YANDEX_UNSTABLE_WINDOW_CLASS="!(class=yandex-browser-unstable)"
FULL_WINDOW_CLASS="(any) & $YANDEX_WINDOW_CLASS & $YANDEX_BETA_WINDOW_CLASS & \
$YANDEX_UNSTABLE_WINDOW_CLASS"

if ! [ -x "$(command -v $DCONF_BIN)" ] || \
   ! [ -x "$(command -v $XMLLINT_BIN)" ] || \
   ! [ -f $COMPIZ_CONFIG ]; then
  exit 1
fi

profiles=`$DCONF_BIN list $COMPIZ_PROFILES`
for profile in $profiles; do
  unredirect_key="$COMPIZ_PROFILES$profile$UNREDIRECT_MATCH_KEY"
  unredirect_value=`$DCONF_BIN read $unredirect_key`

  if [ "$unredirect_value" = "" ]; then
    default_unredirect_value=`$XMLLINT_BIN --xpath $COMPIZ_XPATH $COMPIZ_CONFIG`
    rc=$?
    if [ $rc -ne 0 ]; then
      $DCONF_BIN write $unredirect_key "'$FULL_WINDOW_CLASS'"
    else
      default_unredirect_value=${default_unredirect_value//&amp;/&}
      $DCONF_BIN write $unredirect_key "'($default_unredirect_value) & \
$YANDEX_WINDOW_CLASS & $YANDEX_BETA_WINDOW_CLASS & \
$YANDEX_UNSTABLE_WINDOW_CLASS'"
    fi
    continue
  fi

  unredirect_value="(${unredirect_value:1:${#unredirect_value}-2})"
  prev_unredirect_value=$unredirect_value
  if ! echo "$unredirect_value" | grep -q "$YANDEX_WINDOW_CLASS"; then
    unredirect_value="$unredirect_value & $YANDEX_WINDOW_CLASS"
  fi

  if ! echo "$unredirect_value" | grep -q "$YANDEX_BETA_WINDOW_CLASS"; then
    unredirect_value="$unredirect_value & $YANDEX_BETA_WINDOW_CLASS"
  fi

  if ! echo "$unredirect_value" | grep -q "$YANDEX_UNSTABLE_WINDOW_CLASS"; then
    unredirect_value="$unredirect_value & $YANDEX_UNSTABLE_WINDOW_CLASS"
  fi

  if test "$unredirect_value" != "$prev_unredirect_value"; then
    $DCONF_BIN write $unredirect_key "'$unredirect_value'"
  fi
done
