#!/bin/bash
# This script initializes Regolith Trawn resources and launches Sway.

set -Eeu -o pipefail
source /usr/lib/regolith/regolith-session-common.sh

# Check if NOTIFY_SOCKET is available. This is used as a
# test to see if the session uses systemd
if [ -z "${NOTIFY_SOCKET-}" ]; then
  # Start trawl daemon manually
  trawld&

  # Register with gnome-session so that it does not kill the whole session thinking it is dead.
  if [ -n "${DESKTOP_AUTOSTART_ID-}" ]; then
      dbus-send --print-reply --session --dest=org.gnome.SessionManager "/org/gnome/SessionManager" org.gnome.SessionManager.RegisterClient "string:Regolith-Wayland" "string:$DESKTOP_AUTOSTART_ID"
  fi

  # Export environmentt from Environment.d
  while read -r l; do
      eval export $l
  done < <(/usr/lib/systemd/user-environment-generators/30-systemd-environment-d-generator)
fi

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

load_standard_trawlres
load_regolith_trawlres

# workaround to prevent always loading the default look 
load_regolith_trawlres 

trawl_sway_cleanup

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

# Set XDG_CURRENT_DESKTOP
export XDG_CURRENT_DESKTOP="Regolith-Wayland:GNOME:sway"

# Start sway-regolith
unsupported_gpu=$(trawlcat regolith.sway.unsupported_gpu false)
echo "Regolith is launching Sway with $SWAY_CONFIG_FILE"

if [[ "${unsupported_gpu,,}" == "true" ]]; then
    sway -c "$SWAY_CONFIG_FILE" --unsupported-gpu
else
    sway -c "$SWAY_CONFIG_FILE" 
fi

# Run user's post logout script if script. Post logout means that the wayland session has been terminated.
if [ -f "$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
