#!/bin/bash
# This script initializes Regolith Xresources and launches i3.

# File Locations - Optional User Overrides
USER_XRESOURCE_FILE="$HOME/.Xresources-regolith"
USER_I3_CONFIG_FILE="$HOME/.config/regolith/i3/config"
USER_XRESOURCE_OVERRIDE_FILE="$HOME/.config/regolith/Xresources"
USER_XRESOURCE_SEARCH_PATH="$HOME/.config/regolith/Xresources.d"

# File Locations - System Defaults
DEFAULT_XRESOURCE_FILE="/etc/regolith/styles/root"
DEFAULT_I3_CONFIG_FILE="/etc/regolith/i3/config"

# File Locations - Baseline
BASELINE_XRESOURCE_FILE="$HOME/.Xresources"

# Load default Xresources
if [ -f "$BASELINE_XRESOURCE_FILE" ]; then
    xrdb -merge $BASELINE_XRESOURCE_FILE
fi

# Load Regolith Xresource file or user override
if [ -f "$USER_XRESOURCE_FILE" ]; then
    xrdb -I$USER_XRESOURCE_SEARCH_PATH -merge $USER_XRESOURCE_FILE
else
    xrdb -merge $DEFAULT_XRESOURCE_FILE
fi

# Merge user overrides of Xresources if exists
if [ -f "$USER_XRESOURCE_OVERRIDE_FILE" ]; then
    xrdb -I$USER_XRESOURCE_SEARCH_PATH -merge $USER_XRESOURCE_OVERRIDE_FILE
fi

# Change the quotes in workspace names from double to to single.
# Due to a limitation of the preprocessor they have double quotes.
# The i3-wm workspace command fails with double quotes in the name
xrdb -query |grep i3-wm.workspace.|sed "s/\"/'/g"|xrdb -merge

# Determine i3 config file
if [ -f "$USER_I3_CONFIG_FILE" ]; then
    REGOLITH_I3_CONFIG_FILE=$USER_I3_CONFIG_FILE
else
    REGOLITH_I3_CONFIG_FILE=$DEFAULT_I3_CONFIG_FILE
fi

# Register with gnome-session so that it does not kill the whole session thinking it is dead.
# See https://zork.net/~st/jottings/gnome-i3.html for details
if [ -n "$DESKTOP_AUTOSTART_ID" ]; then
    dbus-send --print-reply --session --dest=org.gnome.SessionManager "/org/gnome/SessionManager" org.gnome.SessionManager.RegisterClient "string:Regolith" "string:$DESKTOP_AUTOSTART_ID"
fi

# Launch i3wm with the Regolith configuration
echo "Regolith is launching i3-gaps with $REGOLITH_I3_CONFIG_FILE"
i3 -c $REGOLITH_I3_CONFIG_FILE

# Close session when i3 exits.
if [ -n "$DESKTOP_AUTOSTART_ID" ]; then
    dbus-send --print-reply --session --dest=org.gnome.SessionManager "/org/gnome/SessionManager" org.gnome.SessionManager.Logout "uint32:1"
fi
