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

set -Eeu -o pipefail

source /usr/lib/regolith/regolith-session-common.sh

# --------- Script Main -----------

load_standard_xres  # ~/.Xresources
load_regolith_xres  # ~/.config/regolith3/Xresources

UPDATE_FLAG_DIR="$HOME/.config/regolith3/flags"
if [ ! -e "$UPDATE_FLAG_DIR" ]; then
    # flag file has not been created, meaning this is first session load
    # in this case, we need to configure some desktop settings from the look
    LOADER_PATH="$($RESOURCE_GETTER regolith.look.loader)"
    if [ -n  "$LOADER_PATH" ]; then
        # Load the look-specific script that has a function called load_look()
        source "$LOADER_PATH"
        # Call look function to update UI
        load_look
    fi
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

resolve_default_config_file
echo "Regolith is launching i3 with $I3_CONFIG_FILE"
i3 -c "$I3_CONFIG_FILE"

# Run user's post logout script if script. Post logout means that the X session is closed at this point.
if [ -e "$USER_POST_LOGOUT_SCRIPT_FILE" ] ; then
    echo "Regolith is launching user post-logout file $USER_POST_LOGOUT_SCRIPT_FILE"
	timeout --verbose 5 bash "$USER_POST_LOGOUT_SCRIPT_FILE"
fi

# 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
