#!/bin/sh
# Starchaser owns crash notices for this window.
export QS_DISABLE_CRASH_HANDLER=1 STARCHASER_QML_APP=settings
# summary: Open a Settings page or an app's details.
# Open Starchaser Settings (optionally at a section: appearance, displays, sound, ...), or at one app's install
# sheet in Software: `starchaser settings app <catalog id>` (the menu's Install pages, install offers), or at an
# installed app's details: `starchaser settings app <source>:<name>` (a right-click on an app row in the menu; with
# '{"ask":"remove"}' after it, they open asking "Remove it?"), or at a
# search in Software: `starchaser settings search <words>` (the Pointer page's "Find more looks").
# Single instance: if it's already running, just show it there. The `--` matters: without it Quickshell reads the
# function name "show" as its own `ipc show` subcommand, the call fails, and a second Settings window opens.
# A new window is started detached, with its output going to a log file, so this command returns at once even when
# its output is captured (a pipe held open by the window would otherwise make the caller wait until it closes).
# Opened from the taskbar: drop what its keeper set for the taskbar alone (drawing without the GPU after full graphics
# memory, the driver's implicit sync), so this window keeps the GPU. A QT_QUICK_BACKEND set by hand stays. QA r179.
if [ "${STARCHASER_KEEPER_PART:-}" = cockpit ]; then unset QT_QUICK_BACKEND __NV_DISABLE_EXPLICIT_SYNC STARCHASER_KEEPER_PART; fi
# Each launch says only what it was asked for: a window started from inside an older one (a Software notice's Open
# Software, from the install helper that window started) would otherwise inherit its app, search or tab and reopen
# that app's sheet instead of Software. The queue's mark goes too, or this window's own installs would think a queue
# reports them and say nothing. QA u802.
unset STARCHASER_SETTINGS_SECTION STARCHASER_SETTINGS_FIND STARCHASER_SOFTWARE_APP STARCHASER_SOFTWARE_CONTEXT \
  STARCHASER_SOFTWARE_SEARCH STARCHASER_SOFTWARE_TAB STARCHASER_SOFTWARE_QUEUE STARCHASER_FIREWALL_LOG_ENTRY \
  STARCHASER_SATELLITES_KIND STARCHASER_SATELLITES_OPEN
CFG="$HOME/.config/quickshell/settings"
# Keep in step with the sections in settings/shell.qml (and SECTIONS in bin/starchaser-ask).
SECTIONS="home apps accounts appearance terminal date-language accessibility satellites displays workspaces ai devices hardware sound bluetooth mouse keyboard network sharing printers updates software backups recovery users mission-control power game notifications shortcuts firewall security privacy about"

usage() {
  cat <<USAGE
Usage: starchaser settings [SECTION [WORD]]
       starchaser settings firewall-log ENTRY-KEY
       starchaser settings music
       starchaser settings seclab
       starchaser settings languages
       starchaser settings installed
       starchaser settings discover
       starchaser settings make-satellite
       starchaser settings app APP-ID [SETUP-JSON]
       starchaser settings search WORDS...
       starchaser settings satellite SATELLITE-ID
       starchaser settings satellite-link

Opens Settings, or brings it to the front if it is already open.
With a SECTION, opens that page; with a WORD too, scrolls the page to where that word is
(starchaser settings ai ask). With "app", opens the install page for one app in Software;
an APP-ID of SOURCE:NAME (repo:vlc, flatpak:org.example.App) opens an installed app's details
instead, and a SETUP-JSON of {"ask":"remove"} opens them asking "Remove it?".
With "search", opens Software searching for those words.
With "firewall-log", opens Firewall > Log at SRC|PROTO|DPORT|IFACE (quote the key).
With "themes", opens Add-ons > Find more showing only themes.
With "satellite", opens one add-on's own settings (or its details, when it has no settings).
With "satellite-link", opens Add-ons at Add from a link, ready for a link to paste.
With "music", opens Apps' Default apps tab (including the Music shortcut).
With "installed", opens Software's Installed tab: every app you installed, with Remove.
With "discover", opens Software's Discover tab, ready to search for an app.
With "make-satellite", opens Add-ons > Make your own, to start your own add-on or theme.

Sections: $SECTIONS
USAGE
}

LOGDIR="${XDG_STATE_HOME:-$HOME/.local/state}/starchaser"
# setsid returns as soon as it forks, so a window whose QML can't load (a file missing after an update) left only
# "Opening Settings…" and nothing after it (QA 20261107-1927 002). So the window is started by a small watcher that
# reads what it writes to the log for up to 20 s, while it runs, and puts "Settings couldn't open" in that notice's place.
# $1 the folder, $2 the log, $3 the opening notice's id (it may be empty)
OPEN='from=$(stat -c %s "$2" 2>/dev/null || echo 0)
qs -p "$1" >>"$2" 2>&1 </dev/null &
pid=$! i=0
while :; do
  alive=1; kill -0 "$pid" 2>/dev/null || alive=
  if tail -c +$((from + 1)) "$2" 2>/dev/null | grep -q "Failed to load configuration"; then
    case "$3" in [1-9]*) set -- "$@" -r "$3" ;; esac
    shift 3
    exec /bin/sh -c '"'"'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'"'"' starchaser notify -a Starchaser -i preferences-system -u normal "$@" \
      -h string:x-canonical-private-synchronous:starchaser-settings-opening "Settings couldn'"'"'t open" \
      "Part of Settings failed to load. Try again, or restart the computer. Details: ~/.local/state/starchaser/settings.log"
  fi
  # Once loaded, the window owns its lifetime and errors. Stop the startup watcher immediately.
  tail -c +$((from + 1)) "$2" 2>/dev/null | grep -q "Configuration Loaded" && exit 0
  [ -n "$alive" ] && [ $i -lt 40 ] || exit 0
  sleep 0.5; i=$((i + 1))
done'
start() {
  # Cold launches compile the window before it appears; acknowledge the request without leaving a history item.
  STARCHASER_SETTINGS_NOTICE_ID=$(timeout 1 /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -p -a Starchaser -i preferences-system -u low -t 5000 -h boolean:transient:true \
    -h string:x-canonical-private-synchronous:starchaser-settings-opening \
    "Opening Settings…" 2>/dev/null) || STARCHASER_SETTINGS_NOTICE_ID=""
  export STARCHASER_SETTINGS_NOTICE_ID
  mkdir -p "$LOGDIR" 2>/dev/null
  if [ -d "$LOGDIR" ] && [ -w "$LOGDIR" ]; then
    # keep only the last 256 KB, so warnings can't grow the log forever
    if [ -f "$LOGDIR/settings.log" ] && [ "$(stat -c %s "$LOGDIR/settings.log" 2>/dev/null || echo 0)" -gt 262144 ]; then
      tail -c 131072 "$LOGDIR/settings.log" >"$LOGDIR/settings.log.tmp" 2>/dev/null && mv -f "$LOGDIR/settings.log.tmp" "$LOGDIR/settings.log"
    fi
    exec setsid -f sh -c "$OPEN" sh "$CFG" "$LOGDIR/settings.log" "$STARCHASER_SETTINGS_NOTICE_ID" >/dev/null 2>&1 </dev/null
  fi
  exec setsid -f qs -p "$CFG" >/dev/null 2>&1 </dev/null
}

# Settings takes over from the Super+Space menu: close it, or the window opens underneath it (the menu sits on
# the overlay layer). hide does nothing when the menu is already closed; no menu running is fine too.
hide_menu() {
  qs -p "$HOME/.config/quickshell/cockpit" ipc call -- menu hide >/dev/null 2>&1 </dev/null || true
  # the desktop's own pop-ups (the clipboard and emoji picker, Quick settings, Power, the top panel) would stay drawn
  # over the new window too (a shortcut or the menu opened it without a click on them): they close as well
  timeout 1 qs -p "$HOME/.config/quickshell/cockpit" ipc call -- cockpit dismissTransient >/dev/null 2>&1 </dev/null || true
}

for a in "$@"; do
  case "$a" in -h|--help|help) usage; exit 0 ;; esac
done
# Keep older USB notification links working after the permission page moves.
if [ "${1:-}" = security ] && [ "${2:-}" = "USB protection" ]; then shift 2; set -- privacy "USB protection" "$@"; fi
case "${1:-}" in
  release-updated)
    [ $# -eq 1 ] || exit 2
    qs -p "$CFG" ipc call -- settings updated >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_UPDATED_RELEASE=1
    start
    ;;
  app)
    if [ -z "${2:-}" ] || [ $# -gt 3 ]; then
      echo "starchaser settings: \"app\" needs an app id and optional setup context" >&2
      usage >&2; exit 2
    fi
    hide_menu
    if [ -n "${3:-}" ]; then
      qs -p "$CFG" ipc call -- settings appSetup "$2" "$3" >/dev/null 2>&1 </dev/null && exit 0
    else
      qs -p "$CFG" ipc call -- settings app "$2" >/dev/null 2>&1 </dev/null && exit 0
    fi
    export STARCHASER_SETTINGS_SECTION=software STARCHASER_SOFTWARE_APP="$2" STARCHASER_SOFTWARE_CONTEXT="${3:-}"
    start ;;
  firewall-log)
    if [ $# -ne 2 ] || [ -z "${2:-}" ]; then
      echo 'starchaser settings: "firewall-log" needs exactly one nonempty entry key' >&2
      usage >&2; exit 2
    fi
    case "$2" in
      '|'*|*'||'*|*'|'*'|'*'|'*'|'*) echo 'starchaser settings: use SRC|PROTO|DPORT|IFACE for the entry key' >&2; exit 2 ;;
      *'|'*'|'*'|'*) ;;
      *) echo 'starchaser settings: use SRC|PROTO|DPORT|IFACE for the entry key' >&2; exit 2 ;;
    esac
    hide_menu
    qs -p "$CFG" ipc call -- settings firewallLog "$2" >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=firewall STARCHASER_FIREWALL_LOG_ENTRY="$2"
    start ;;
  seclab)
    if [ $# -gt 1 ]; then usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings showAt security "Security lab" >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=security STARCHASER_SETTINGS_FIND="Security lab"
    start ;;
  languages)
    if [ $# -gt 1 ]; then usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings softwareTab "$1" >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=software STARCHASER_SOFTWARE_TAB="$1"
    start ;;
  discover)
    if [ $# -gt 1 ]; then echo "starchaser settings: \"discover\" takes nothing after it" >&2; usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings softwareTab discover >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=software STARCHASER_SOFTWARE_TAB=discover
    start ;;
  installed)
    if [ $# -gt 1 ]; then echo "starchaser settings: \"installed\" takes nothing after it" >&2; usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings softwareTab installed >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=software STARCHASER_SOFTWARE_TAB=installed
    start ;;
  make-satellite)
    # Help's "Make your own add-on or theme": Satellites on its Make your own tab
    if [ $# -gt 1 ]; then echo "starchaser settings: \"make-satellite\" takes nothing after it" >&2; usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings satellitesWant @make >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=satellites STARCHASER_SATELLITES_KIND=@make
    start ;;
  themes)
    if [ $# -gt 1 ]; then echo "starchaser settings: \"themes\" takes nothing after it" >&2; usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings themes >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=satellites STARCHASER_SATELLITES_KIND=theme
    start ;;
  satellite)
    # a taskbar item's right-click "Satellite settings…": that add-on's own settings, not the list of them
    case "${2:-}" in
      ''|*[!a-z0-9-]*|-*|*-|*--*) echo "starchaser settings: \"satellite\" needs a satellite id" >&2; usage >&2; exit 2 ;;
    esac
    if [ $# -gt 2 ]; then usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings satellite "$2" >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=satellites STARCHASER_SATELLITES_OPEN="$2"
    start ;;
  satellite-link)
    # the menu's Install > Theme or add-on from a link: Add-ons with Add from a link open
    if [ $# -gt 1 ]; then echo "starchaser settings: \"satellite-link\" takes nothing after it" >&2; usage >&2; exit 2; fi
    hide_menu
    qs -p "$CFG" ipc call -- settings satellitesWant @link >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=satellites STARCHASER_SATELLITES_KIND=@link
    start ;;
  music)
    if [ $# -gt 1 ]; then echo "starchaser settings: \"music\" takes nothing after it" >&2; usage >&2; exit 2; fi
    starchaser music hide >/dev/null 2>&1 </dev/null || true
    hide_menu
    qs -p "$CFG" ipc call -- settings softwareTab defaults >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=apps STARCHASER_SOFTWARE_TAB=defaults
    start ;;
  search)
    shift
    if [ -z "$*" ]; then
      echo "starchaser settings: \"search\" needs some words to search for" >&2
      usage >&2; exit 2
    fi
    hide_menu
    qs -p "$CFG" ipc call -- settings search "$*" >/dev/null 2>&1 </dev/null && exit 0
    export STARCHASER_SETTINGS_SECTION=software STARCHASER_SOFTWARE_SEARCH="$*"
    start ;;
  startup|custom-shortcuts)
    if [ $# -gt 2 ]; then usage >&2; exit 2; fi ;;
  "") ;;
  -*) echo "starchaser settings: unknown option \"$1\". Run 'starchaser settings --help' for more help." >&2; usage >&2; exit 2 ;;
  *)
    case " $SECTIONS " in
      *" $1 "*) ;;
      *) echo "starchaser settings: unknown section \"$1\". Run 'starchaser settings --help' for more help." >&2; echo "Sections: $SECTIONS" >&2; exit 2 ;;
    esac
    if [ $# -gt 2 ]; then echo "starchaser settings: too many arguments" >&2; usage >&2; exit 2; fi ;;
esac

hide_menu
if [ -n "${2:-}" ]; then
  qs -p "$CFG" ipc call -- settings showAt "$1" "$2" >/dev/null 2>&1 </dev/null && exit 0
  export STARCHASER_SETTINGS_FIND="$2"
else
  qs -p "$CFG" ipc call -- settings show "${1:-}" >/dev/null 2>&1 </dev/null && exit 0
fi
# Leave a plain launch unspecified so Settings can resume a pending firewall change or the last page.
export STARCHASER_SETTINGS_SECTION="${1:-}"
start
