#!/bin/bash

# omarchy:summary=Shared helpers for generating locales and handing them to the session (source this, don't run it).
# omarchy:hidden=true

# Sourced by omarchy-language (Setup > Region > Language) and omarchy-region-formats
# (Setup > Region > Formats).

locale_generated() {
  # locale -a normalizes punctuation away (en_US.utf8), so compare squashed.
  local want available
  want=$(echo "$1" | tr -cd 'a-zA-Z0-9' | tr '[:upper:]' '[:lower:]')
  available=" $(locale -a 2>/dev/null | tr -cd 'a-zA-Z0-9\n' | tr '[:upper:]' '[:lower:]' | tr '\n' ' ') "
  [[ $available == *" $want "* ]]
}

# Generating a locale is the one step that needs root. The helper does it from
# a registry code alone, at the path etc/sudoers.d/omarchy-locale-generate
# names, so the passwordless rule matches even where $OMARCHY_PATH points at a
# checkout; without the package (a bare dev checkout) the checkout's own copy
# runs, behind a password prompt.
generator=/usr/bin/omarchy-locale-generate
[[ -x $generator ]] || generator=$OMARCHY_PATH/bin/omarchy-locale-generate

# True when sudo would run the helper for this code without a password. `sudo
# -l` alone only says a command is permitted, which the blanket %wheel rule
# answers yes to; the long listing prints the matched entry's tags, so
# !authenticate is the grant and nothing else. Under -n it prompts for
# nothing, so a machine whose omarchy-settings predates the grant falls
# through to a prompt instead of failing.
generator_is_passwordless() {
  sudo -n -l -l "$generator" "$1" 2>/dev/null | grep -q '!authenticate'
}

# generate_locale <registry code> <locale>
generate_locale() {
  local code=$1 locale=$2
  locale_generated "$locale" && return

  if (( EUID == 0 )); then
    "$generator" "$code"
  elif generator_is_passwordless "$code"; then
    sudo -n "$generator" "$code"
  elif [[ -t 0 ]]; then
    # A terminal can carry sudo's own prompt.
    sudo "$generator" "$code"
  else
    # Picked from the menu there is no terminal, so polkit asks on screen.
    pkexec "$generator" "$code"
  fi
}

# apply_session_env <name>=<value>...
#
# Hands locale variables to the running session; the uwsm env file the caller
# wrote carries them to the next login. uwsm-app runs apps in a scope, which
# keeps the environment of whatever launched it: Hyprland for bindings, the
# shell for the launcher. So Hyprland takes each new value, its third argument
# passing it on to the systemd and D-Bus activation environments services
# start from, and the shell is respawned from Hyprland to inherit them. An
# empty value counts as unset for every locale category. Apps already running
# keep what they started with.
apply_session_env() {
  [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]] || return 0

  local assignment
  for assignment in "$@"; do
    hyprctl eval "hl.env(\"${assignment%%=*}\", \"${assignment#*=}\", true)" >/dev/null 2>&1 || return 0
  done
  omarchy-restart-shell >/dev/null 2>&1 || true
}
