#!/bin/bash

# apply instantOS dpi settings

DPI="$(iconf dpi)"

# ensure xresources keeps its unmodified status if modified by the OS
checkxresources() {
    if ! imosid info ~/.Xresources; then
        XUNMODIFIED=true
    else
        unset XUNMODIFIED
    fi

}

finishxresources() {
    if [ -n "$XUNMODIFIED" ]; then
        imosid compile ~/.Xresources
        unset XUNMODIFIED
    fi
}

resetdpi() {
    echo "resetting dpi"
    sed -i '/^Xft\.dpi/d' ~/.Xresources
    sed -i '/^\*dpi/d' ~/.Xresources
    sed -i '/^st.font/d' ~/.Xresources
}

appendpi() {
    echo "setting dpi to $DPI"
    echo "Xft.dpi: $DPI" >>~/.Xresources
    echo "*dpi: $DPI" >>~/.Xresources

    # recalculate st font size based on dpi
    # as st does not scale with dpi by default
    NEWFONTSIZE="$(echo "( $DPI / 96 ) * 15" | bc -l | grep -o '^[^\.]*')"
    sed -i '/^st.font/d' ~/.Xresources
    echo "st.font: Fira Code Nerd Font Mono:pixelsize=$NEWFONTSIZE:antialias=true:autohint=true" >>~/.Xresources
    echo "st.font2: JoyPixels:pixelsize=$NEWFONTSIZE:antialias=true:autohint=true" >>~/.Xresources
}

checkxresources

if [ -z "$DPI" ]; then
    resetdpi
    finishxresources
    exit
fi

[ "$DPI" -eq "$DPI" ] || exit

# resetting
if [ "$DPI" = "96" ]; then
    resetdpi
    finishxresources
    exit
fi

if ! [ -e .Xresources ]; then
    echo "initializing xresources"
    touch ~/.Xresources
    appendpi "$DPI"
else
    resetdpi
    appendpi "$DPI"
fi

finishxresources
