#!/bin/bash

# omarchy:summary=Draw the current icon set in the current theme's colors
# omarchy:hidden=true

# An icon set is a directory of app icons named after the Icon= of the desktop
# entries they are for: <icon name>.svg.tpl is drawn in the theme's colors, and
# <icon name>.svg is used as it is. Omarchy's own sets live in icons,
# the user's in ~/.config/omarchy/icons, and `omarchy icons set` picks the one
# in use. A set and a theme are chosen separately: the theme only ever supplies
# the colors, so it ships no icons of its own.
#
# A user's set with the name of a built-in one is laid over it, icon by icon, so
# ~/.config/omarchy/icons/papercraft/<icon name>.svg.tpl redraws a single icon
# of the default set. A set that isn't there draws nothing, which is how the
# `original` set brings every app's own icon back.
#
# This runs after the theme is on screen, so drawing icons never holds up a
# switch. The icons render into a scratch dir and each one replaces its
# predecessor in ~/.local/state/omarchy/current/icons with a rename, so an app
# or the shell reading one mid-switch gets the old icon or the new, never a
# missing or half-written one.
#
# Each icon is linked by name over the packaged hicolor icon once; the link
# never changes after that. An icon the user put there themselves is kept. An
# icon the set no longer draws goes, and its link with it, and the packaged
# icon shows again: after a switch to a set without it, or under a theme whose
# colors can't be read.
#
# The shell watches icons.revision and redraws the icons when it changes.

CURRENT="$HOME/.local/state/omarchy/current"
THEME="$CURRENT/theme"
ICONS="$CURRENT/icons"
MODEL_FALLBACKS="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agent-local/icons"
LINKS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps"

shopt -s nullglob

# Quick switches can start runs that overlap. One at a time, and the set and
# theme are read once the lock is held, so the last one to run draws what is
# current and an older choice never lands last. omarchy-icons-set writes the
# set's name under the same lock.
mkdir -p "$CURRENT"
exec 7>"$CURRENT/.icons.lock"
flock 7

SET=$(omarchy-icons-current --id)
BUILT_IN_SET="$OMARCHY_PATH/icons/$SET"
USER_SET="$HOME/.config/omarchy/icons/$SET"

scratch=$(mktemp -d "$CURRENT/.icons.XXXXXX")
trap 'rm -rf "$scratch"' EXIT
mkdir "$scratch/set" "$scratch/out"

# Run a file command in bounded argv chunks so very large custom icon sets
# cannot hit ARG_MAX and abort mid-sync.
run_batched() {
  local -a cmd=()
  while (( $# )) && [[ $1 != "--" ]]; do
    cmd+=("$1")
    shift
  done
  (( $# )) && shift
  (( $# > 0 )) || return 0
  printf '%s\0' "$@" | xargs -0 -r "${cmd[@]}" --
}

# The user's set goes over the built-in one of the same name. An icon is given
# once, so the user's drawing replaces the built-in template of that name and
# the other way around. A set cloned from a git repo holds whatever its author
# pushed, so its symlinks, which point wherever they chose, are left out.
declare -A selected=()
for dir in "$BUILT_IN_SET" "$USER_SET"; do
  for icon in "$dir"/*.svg "$dir"/*.svg.tpl; do
    [[ -f $icon ]] || continue
    [[ -L $icon && -e $dir/.git ]] && continue
    name=${icon##*/}
    name=${name%.tpl}
    selected[$name]=$icon
  done
done

run_batched cp -t "$scratch/set" -- "${selected[@]}" || exit 1

static_svgs=("$scratch/set"/*.svg)
run_batched mv -t "$scratch/out" -- "${static_svgs[@]}" || exit 1
omarchy-theme-set-templates --icons "$THEME" "$scratch/out" "$scratch/set"

mkdir -p "$ICONS" "$LINKS"
declare -A drawn=()
rendered_svgs=("$scratch/out"/*.svg)
missing_links=()
run_batched mv -f -t "$ICONS" -- "${rendered_svgs[@]}" || exit 1
for icon in "${rendered_svgs[@]}"; do
  name=${icon##*/}
  drawn[$name]=1
  # A working icon of the user's own stays; a dangling link or Omarchy's own
  # local-model fallback link is replaced by the active icon set.
  if [[ ! -e $LINKS/$name ]] ||
    [[ -L $LINKS/$name && $(readlink "$LINKS/$name") == "$MODEL_FALLBACKS/$name" ]]; then
    missing_links+=("$ICONS/$name")
  fi
done
links_changed=0
if (( ${#missing_links[@]} > 0 )); then
  run_batched ln -sfn -t "$LINKS" -- "${missing_links[@]}"
  links_changed=1
fi

# What the last run drew and this one didn't.
for icon in "$ICONS"/*.svg; do
  name=${icon##*/}
  link="$LINKS/$name"
  [[ -z ${drawn[$name]:-} ]] || continue
  rm -f "$icon"
  if [[ -L $link && $(readlink "$link") == "$icon" ]]; then
    if [[ -f $MODEL_FALLBACKS/$name ]]; then
      ln -sfn "$MODEL_FALLBACKS/$name" "$link"
    else
      rm "$link"
    fi
    links_changed=1
  fi
done

draw_rev=${EPOCHREALTIME//[!0-9]/}
links_rev=0
if [[ -r $CURRENT/icons.revision ]]; then
  IFS=$'\t ' read -r _ prev_links_rev _ <"$CURRENT/icons.revision" || true
  [[ $prev_links_rev =~ ^[0-9]+$ ]] && links_rev=$prev_links_rev
fi
if (( links_changed )); then
  links_rev=$draw_rev
fi

printf '%s\t%s\n' "$draw_rev" "$links_rev" >"$CURRENT/icons.revision"
