#!/bin/bash
set -eu

# Based on https://github.com/vincentbernat/awesome-configuration/blob/master/bin/xsettingsd-setup
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}"

BLUR_STRENGTH=10
CORNER_RADIUS=9
CURSOR_SIZE=16

xrdbget() {
    set -o pipefail
    xrdb -query | grep -i -m1 "$1" | sed 's/^.*:\s//g' || echo "$2"
}

xsetting_bool() {
    case "$1" in
        true) echo 1;;
        false) echo 0;;
        default) echo -1;;
        *) echo -1;;
    esac
}


if [ -z "$1" ] || [ "$1" -gt 200 ] || [ "$1" -lt 96 ]; then
    >&2 printf "Usage\n\t%s: value\n\n  value\t Value must be within 96-200 inclusive\n" "$(basename "$0")"
    exit 1
fi

dpi=$1
scale=$(( dpi/96 ))
cursor=$(( (dpi*CURSOR_SIZE)/96 ))

# Update picom scale
sed -i -e "s/strength =.*$/strength = $(( (dpi*BLUR_STRENGTH)/96 ));/" \
    -e "s/corner-radius =.*$/corner-radius = $(( (dpi*CORNER_RADIUS)/96 ));/" \
    "$CONF_DIR/picom/picom.conf" &

# Build xsettingsd.conf
mkdir -p "$CONF_DIR/xsettingsd"
{
    cat "$CONF_DIR/xsettingsd.local" 2>/dev/null || :
    echo "Xcursor/size $cursor"
    echo "Gtk/CursorThemeSize $cursor"
    echo "Gtk/CursorThemeName \"$(xrdbget Xcursor.theme Adwaita)\""
    echo "Xft/HintStyle \"$(xrdbget Xft.hintstyle hintfull)\""
    echo "Xft/Hinting $(xsetting_bool "$(xrdbget Xft.hinting default)")"
    echo "Xft/RGBA \"$(xrdbget Xft.rgba rgb)\""
    echo "Xft/DPI $(( dpi*1024 ))"
    echo "Gdk/WindowScalingFactor $scale"
    echo "Gdk/UnscaledDPI $(( dpi*1024/scale ))"
} > "$CONF_DIR/xsettingsd/xsettingsd.conf"

xrdb -merge <<EOF &
Xft.dpi: $dpi
Xcursor.size: $cursor
EOF
xrandr --dpi "$dpi" &
systemctl --user try-reload-or-restart xsettingsd &
wait

systemctl --user try-reload-or-restart \
    i3 \
    polybar@i3bar &
systemctl --user try-restart \
    dunst &

wait