#!/bin/bash
# This script will be called after i3 starts. It's purpose is to do things
# that only make sense for the first time the user starts Regolith.

UPDATE_FLAG_DIR="$HOME/.config/regolith3/flags"
UPDATE_FLAG_PATH="$UPDATE_FLAG_DIR/show-shortcuts"
TERM_PROFILE_PATH="$UPDATE_FLAG_DIR/term-profile"

# Read resources from trawl in the sway session, from Xresources in X11.
if [ "${XDG_SESSION_TYPE-}" == "wayland" ]; then
    RESOURCE_GETTER=trawlcat
else
    RESOURCE_GETTER=xrescat
fi

TERM_PROFILE_ENABLED="$($RESOURCE_GETTER gnome.terminal.update true 2> /dev/null)"

if [ ! -f "$UPDATE_FLAG_PATH" ]; then
    # Use the active look's stylesheet, as the help keybinding does.
    STYLESHEET="$($RESOURCE_GETTER ilia.stylesheet "" 2> /dev/null)"
    if [ -z "$STYLESHEET" ] || [ ! -f "$STYLESHEET" ]; then
        STYLESHEET=/usr/share/regolith-look/default/ilia.css
    fi

    if [ -f "$STYLESHEET" ]; then
        ilia -p keybindings -a -t "$STYLESHEET" &
    else
        ilia -p keybindings -a &
    fi

    mkdir -p "$UPDATE_FLAG_DIR"
    touch "$UPDATE_FLAG_PATH"
fi

if [[ ! -z "$(command -v gnome-terminal 2> /dev/null)" && "$TERM_PROFILE_ENABLED" == "true" && ! -f "$TERM_PROFILE_PATH" ]]; then
    # Only mark the profile as done once the helper has succeeded, so a
    # failed setup is retried at the next login.
    if /usr/share/regolith-ftue/regolith-init-term-profile; then
        mkdir -p "$UPDATE_FLAG_DIR"
        touch "$TERM_PROFILE_PATH"
    else
        HELPER_RC=$?
        echo "regolith-ftue: GNOME Terminal profile setup failed (exit $HELPER_RC); it will be retried at the next login" >&2
        exit "$HELPER_RC"
    fi
fi
