#!/bin/bash

# omarchy:summary=Shared helpers for editing ~/.config/omarchy/shell.json (source this, don't run it).
# omarchy:hidden=true

CONFIG_FILE="$HOME/.config/omarchy/shell.json"
DEFAULTS_FILE="$OMARCHY_PATH/config/omarchy/shell.json"

fail() {
  echo "${0##*/}: $*" >&2
  exit 1
}

refresh_shell_config() {
  if ! omarchy-shell shell reloadConfig >/dev/null 2>&1; then
    omarchy-shell -q shell rescanPlugins >/dev/null 2>&1 || true
  fi
}

source_file() {
  if [[ -s $CONFIG_FILE ]]; then
    printf '%s\n' "$CONFIG_FILE"
  else
    printf '%s\n' "$DEFAULTS_FILE"
  fi
}

# jq pipeline that normalizes shell.json into a well-shaped object with
# version=1, a plugins array, and, when it has a bar,
# bar.layout.{left,centerBegin,center,centerEnd,right} arrays. Every mutation
# pipes through this. A file without a bar keeps none, so the shell's fallback
# bar stays.
NORMALIZE='
  def object_or_empty: if type == "object" then . else {} end;
  def array_or_empty: if type == "array" then . else [] end;
  object_or_empty
  | .version = 1
  | if (.bar | type) == "object" then
      .bar.layout = (.bar.layout | object_or_empty)
      | .bar.layout.left = (.bar.layout.left | array_or_empty)
      | .bar.layout.centerBegin = (.bar.layout.centerBegin | array_or_empty)
      | .bar.layout.center = (.bar.layout.center | array_or_empty)
      | .bar.layout.centerEnd = (.bar.layout.centerEnd | array_or_empty)
      | .bar.layout.right = (.bar.layout.right | array_or_empty)
    else
      del(.bar)
    end
  | .plugins = (.plugins | array_or_empty)
'

# Apply a jq program to the source file and atomically write the result to the
# user config, then refresh the running shell. Extra args after the program are
# forwarded to jq (e.g. --arg/--argjson).
_SHELL_CONFIG_TMP=""
cleanup_shell_config_tmp() {
  if [[ -n $_SHELL_CONFIG_TMP ]]; then rm -f "$_SHELL_CONFIG_TMP"; fi
}
trap cleanup_shell_config_tmp EXIT

commit() {
  local program="$1" target
  shift
  mkdir -p "$(dirname "$CONFIG_FILE")"
  # A shell.json linked from dotfiles is written where it points, so it stays a link,
  # unless the link is dangling or read-only, when it is replaced as before.
  target=$(readlink -f "$CONFIG_FILE" 2>/dev/null) || target=""
  [[ -n $target && -w $(dirname "$target") ]] || target="$CONFIG_FILE"
  _SHELL_CONFIG_TMP=$(mktemp "$target.XXXXXX")
  jq -S -e "$@" "$program" "$(source_file)" >"$_SHELL_CONFIG_TMP" || fail "could not update shell config"
  mv "$_SHELL_CONFIG_TMP" "$target"
  _SHELL_CONFIG_TMP=""
  refresh_shell_config
}
