#!/bin/bash
# This is a helper script to perform common tasks with regolith looks.

set -Eeu -o pipefail

# Load common functions
source /usr/lib/regolith/regolith-session-common.sh

if [ "$#" -lt 1 ]; then
    echo "Usage: regolith-look <command>"
    echo "Actions: "
    echo "    refresh - Update the current session look based on Xresources values"
    echo "    list - Display currently installed looks in the /usr/share/regolith-look directory"
    echo "    set <look> - Write a global override file in the user dir to specify the desired look"
    exit 1
fi

COMMAND=$1

WM_RELOAD="i3-msg -q restart"

# sway's reload applies default_border, default_floating_border and the gaps
# only to windows and workspaces created afterwards, while i3's restart applies
# them to the open ones too. Give the open windows and workspaces what a new
# one gets from Regolith's sway config: the default borders, the border its
# for_window rule sets on every window, and the gaps. sway expands the config's
# variables in these commands. A command that matches no window, or whose
# variables the config doesn't set, fails and is skipped.
sway_restyle_existing() {
    local cmd
    for cmd in \
        '[tiling] border $wm.window.border.style $wm.window.border.size' \
        '[floating] border $wm.floatingwindow.border.style $wm.floatingwindow.border.size' \
        '[title=".*"] border pixel $wm.window.border.size' \
        'gaps inner all set $wm.gaps.inner.size' \
        'gaps outer all set $wm.gaps.outer.size'; do
        swaymsg -q "$cmd" >/dev/null 2>&1 || true
    done
}

refresh() {
    if [[ ${XDG_SESSION_TYPE-} == "wayland" ]]; then
        WM_RELOAD="swaymsg reload"
        reload_sway_resources
        swaymsg -t send_tick '{"status": "reload_pending"}'
    else
        reload_i3_resources
    fi

    # Determine if Look loader script is available
    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

        # restart window manager after merging Xresources
        $WM_RELOAD
        if [[ ${XDG_SESSION_TYPE-} == "wayland" ]]; then
            sway_restyle_existing
        fi
    else
        echo "No look loader script specified, no UI changes"
    fi
}

# Upsert Xresource key regolith.look.path and refresh session
set_look() {
    if [ ! -d "$LOOK_PATH" ]; then
        echo "Aborting, invalid look directory: $LOOK_PATH"
        exit 1
    fi

    # Unset any existing values
    if [ -e "$USER_XRESOURCE_OVERRIDE_FILE" ]; then
	# remove existing declaration comments
        sed -i '/^!regolith.look.path/d' "$USER_XRESOURCE_OVERRIDE_FILE"

        # disable existing declaration
        sed -i 's/^regolith.look.path/\!regolith.look.path/g' "$USER_XRESOURCE_OVERRIDE_FILE"
    fi

    # add new declaration
    echo "regolith.look.path: $LOOK_PATH" >> "$USER_XRESOURCE_OVERRIDE_FILE"

    # refresh rebuilds the resources from the files, so it reads the new look
    refresh
}

if [ "$COMMAND" == "refresh" ]; then
    refresh
elif [ "$COMMAND" == "set" ]; then
    LOOK_NAME=${2-}
    if [ -z "$LOOK_NAME" ]; then
        echo "Must specify a look to set." >&2
        exit 1
    else
        LOOK_PATH="$DEFAULT_LOOK_ROOT/$LOOK_NAME"

        if [ -d "$LOOK_PATH" ]; then
            set_look
        else
            LOOK_PATH="$USER_LOOK_ROOT/$LOOK_NAME"
            if [ -d "$LOOK_PATH" ]; then
                set_look
            else
                echo "Unable to find look $LOOK_NAME in $DEFAULT_LOOK_ROOT or $USER_LOOK_ROOT" >&2
                echo "Run 'regolith-look list' to see the installed looks." >&2
                exit 1
            fi
        fi
    fi
elif [ "$COMMAND" == "list" ]; then
    if [ -d "$USER_LOOK_ROOT" ]; then
        find {"$DEFAULT_LOOK_ROOT","$USER_LOOK_ROOT"} -maxdepth 1 -mindepth 1 -type d -printf '%f\n' | sort
    else
        find "$DEFAULT_LOOK_ROOT" -maxdepth 1 -mindepth 1 -type d -printf '%f\n' | sort
    fi
else
    echo "Unrecognized command: $COMMAND"
    exit 1
fi
