#!/bin/bash

# omarchy:summary=Set the active bar option, position, and transparency
# omarchy:group=bar
# omarchy:args=use <id> | reset | defaults | position <top|bottom|left|right> | transparent <true|false>
# omarchy:examples=omarchy bar use local.neon-bar | omarchy bar reset | omarchy bar defaults | omarchy bar position top | omarchy bar transparent true

set -euo pipefail

CONFIG_FILE="$HOME/.config/omarchy/shell.json"
OMARCHY_ROOT="${OMARCHY_PATH:-}"
DEFAULTS_FILE="$OMARCHY_ROOT/config/omarchy/shell.json"

usage() {
  cat <<USAGE
Usage: omarchy bar <command> [args...]

  use <id>                             Use a bar option as the active bar
  reset                                Return to the built-in Omarchy bar
  defaults                             Restore the default bar and service widgets
  position <top|bottom|left|right>     Bar position
  transparent <true|false>             Bar transparency

Bar widgets are added, moved, removed, and configured with 'omarchy bar plugin'.

Examples:
  omarchy bar use local.neon-bar
  omarchy bar reset
  omarchy bar defaults
  omarchy bar position top
  omarchy bar transparent true
USAGE
}

fail() {
  echo "omarchy-bar: $*" >&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, bar.layout.{left,center,right} arrays, and plugins array.
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
  | .bar = (.bar | object_or_empty)
  | .bar.layout = (.bar.layout | object_or_empty)
  | .bar.layout.left = (.bar.layout.left | array_or_empty)
  | .bar.layout.center = (.bar.layout.center | array_or_empty)
  | .bar.layout.right = (.bar.layout.right | array_or_empty)
  | .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).
_BAR_TMP=""
cleanup_bar_tmp() {
  if [[ -n ${_BAR_TMP:-} ]]; then rm -f "$_BAR_TMP"; fi
}
trap cleanup_bar_tmp EXIT

commit() {
  local program="$1"
  shift
  mkdir -p "$(dirname "$CONFIG_FILE")"
  _BAR_TMP=$(mktemp)
  jq -S -e "$@" "$program" "$(source_file)" >"$_BAR_TMP" || fail "could not update shell config"
  mv "$_BAR_TMP" "$CONFIG_FILE"
  _BAR_TMP=""
  refresh_shell_config
}

# ------------------------------------------------------------------ validation

bar_option_exists() {
  omarchy-plugin-catalog | jq -e --arg id "$1" '
    any(.[]; (.kinds | index("bar")) and .barPath != null and .id == $id)
  ' >/dev/null
}

# -------------------------------------------------------------------- commands

cmd_use() {
  local plugin="${1:-}"
  [[ -n $plugin ]] || fail "bar option id is required"
  [[ $# -eq 1 ]] || fail "use takes a single bar option id"
  if [[ $plugin == "default" || $plugin == "built-in" ]]; then
    plugin="omarchy.bar"
  fi
  bar_option_exists "$plugin" || fail "$plugin is not a known bar option; run 'omarchy plugin list'"

  if [[ $plugin == "omarchy.bar" ]]; then
    commit "$NORMALIZE | del(.bar.id)"
  else
    commit "$NORMALIZE | .bar.id = \$plugin" --arg plugin "$plugin"
  fi
  echo "Using $plugin as the active bar"
}

cmd_defaults() {
  (( $# == 0 )) || fail "defaults does not take arguments"
  # Restore the whole default bar, then re-add widgets for services the user
  # actually has installed (they aren't in the shipped default layout).
  commit "$NORMALIZE | .bar = \$defaults[0].bar" --slurpfile defaults "$DEFAULTS_FILE"
  local service
  for service in dropbox tailscale; do
    if "omarchy-installed-service-$service"; then
      omarchy-bar-plugin add "omarchy.$service"
    fi
  done
  echo "Restored the default Omarchy bar"
}

cmd_position() {
  local position="${1:-}"
  [[ -n $position ]] || fail "position is required"
  [[ $# -eq 1 ]] || fail "position takes a single value"
  [[ $position =~ ^(top|bottom|left|right)$ ]] || fail "position must be top, bottom, left, or right"
  commit "$NORMALIZE | .bar.position = \$position" --arg position "$position"
  echo "Bar position set to $position"
}

cmd_transparent() {
  local transparent="${1:-}"
  [[ -n $transparent ]] || fail "transparent is required"
  [[ $# -eq 1 ]] || fail "transparent takes a single value"
  [[ $transparent =~ ^(true|false)$ ]] || fail "transparent must be true or false"
  commit "$NORMALIZE | .bar.transparent = \$transparent" --argjson transparent "$transparent"
  echo "Bar transparency set to $transparent"
}

# --------------------------------------------------------------------- dispatch

command="${1:-}"
[[ $# -gt 0 ]] && shift || true

case "$command" in
  use)
    cmd_use "$@"
    ;;
  reset)
    (( $# == 0 )) || fail "reset does not take arguments"
    cmd_use omarchy.bar
    ;;
  defaults)
    cmd_defaults "$@"
    ;;
  position)
    cmd_position "$@"
    ;;
  transparent)
    cmd_transparent "$@"
    ;;
  plugin)
    exec omarchy-bar-plugin "$@"
    ;;
  add | move | remove | rm | drop | set | replace)
    fail "bar widgets are managed with: omarchy bar plugin $command ..."
    ;;
  -h | --help | help | "")
    usage
    ;;
  *)
    fail "unknown command: $command"
    ;;
esac
