#!/usr/bin/env bash

WM="marco"
COMP="picom"
BACKEND="glx"
VSYNC="--vsync"

if [ ! -x "$(which "${WM}")" ] || [ ! -x "$(which "${COMP}")" ]; then
    echo "ERROR! Can't find required components for ${WM} or ${COMP}."
    exit 1
fi

# Disable vsync is the NVIDIA compositor is enabled.
if [ -x "$(which nvidia-settings)" ]; then
    if nvidia-settings -q CurrentMetaMode -t | grep ForceCompositionPipeline=On; then
        VSYNC="--no-vsync"
    fi
fi

UNAME="$(id -un)"
killall --user "${UNAME}" compton 2>/dev/null
killall --user "${UNAME}" "${COMP}" 2>/dev/null
killall --user "${UNAME}" "${WM}" 2>/dev/null

# Allow users to override the defaults by creating their own config
# for this wrapper.
if [ -f "${HOME}/.config/${WM}-${COMP}.conf" ]; then
    ${COMP} \
        --daemon \
        --config "${HOME}/.config/${WM}-${COMP}.conf"
else
    ${COMP} \
        --daemon \
        --config /dev/null \
        --backend ${BACKEND} ${VSYNC} \
        --detect-rounded-corners \
        --detect-client-leader \
        --detect-transient \
        --detect-client-opacity \
        --glx-no-stencil \
        --no-use-damage \
        --inactive-opacity-override \
        --mark-wmwin-focused \
        --mark-ovredir-focused \
        --shadow-radius=24 --shadow-opacity=0.225 --shadow-offset-x=-24 --shadow-offset-y=-24 \
        --shadow --no-dock-shadow --no-dnd-shadow \
        --fading \
        --fade-delta=8 \
        --no-fading-destroyed-argb \
        --xinerama-shadow-crop \
        --use-ewmh-active-win \
        --unredir-if-possible \
        --unredir-if-possible-exclude "class_g = 'Mate-screensaver'" \
        --shadow-exclude "! name~=''" \
        --shadow-exclude "name = 'Notification'" \
        --shadow-exclude "name = 'Docky'" \
        --shadow-exclude "class_g = 'albert'" \
        --shadow-exclude "class_g = 'Conky'" \
        --shadow-exclude "class_g = 'Kupfer'" \
        --shadow-exclude "class_g = 'Plank'" \
        --shadow-exclude "class_g = 'Synapse'" \
        --shadow-exclude "class_g = 'Ulauncher'" \
        --shadow-exclude "class_g ?= 'Notify-osd'" \
        --shadow-exclude "class_g ?= 'Cairo-dock'" \
        --shadow-exclude "class_g = 'Cairo-clock'" \
        --shadow-exclude "class_g = 'Firefox' && argb" \
        --shadow-exclude "_GTK_FRAME_EXTENTS@:c" \
        --shadow-exclude "_NET_WM_STATE@:32a *= '_NET_WM_STATE_HIDDEN'" \
        --shadow-exclude "_NET_WM_STATE@:32a *= '_NET_WM_STATE_MAXIMIZED'"
fi

# Replace window manager and force compositing off.
${WM} --no-composite --replace &
