#!/usr/bin/env bash

# omarchy:summary=Apply the current theme's light or dark mode and background to macOS
# omarchy:hidden=true

# macOS keeps the appearance and the desktop picture in System Settings, the
# way GNOME keeps its colour scheme in dconf: this is the Mac twin of
# omarchy-theme-set-gnome, run from omarchy-theme-set's post-theme commands.
# Anywhere but a Mac there is nothing to set.
[[ $(uname -s) == Darwin ]] || exit 0

THEME_DIR="$HOME/.local/state/omarchy/current/theme"
BACKGROUND_LINK="$HOME/.local/state/omarchy/current/background"

# omarchy-theme-color resolves mode from colors.toml (`mode = "light"`), a
# legacy light.mode marker beside it, or background luminance for user themes.
mode=$(omarchy-theme-color --file "$THEME_DIR/colors.toml" mode)

dark=true
[[ $mode == "light" ]] && dark=false

# System Events is what switches every running app; a `defaults write` of
# AppleInterfaceStyle changes nothing that is already open.
osascript -e "tell application \"System Events\" to tell appearance preferences to set dark mode to $dark" >/dev/null

# The background link is the one omarchy-theme-set just moved. The path
# travels as an argument, so a quote in a file name is a file name.
background=$(readlink -f "$BACKGROUND_LINK" 2>/dev/null || true)
if [[ -f $background ]]; then
  osascript \
    -e 'on run argv' \
    -e 'tell application "System Events" to set picture of every desktop to (item 1 of argv)' \
    -e 'end run' \
    "$background" >/dev/null
fi
