#!/usr/bin/env sh
set -eu
launcher_path=$0
link_depth=0
while [ -L "$launcher_path" ]; do
  link_depth=$((link_depth + 1))
  [ "$link_depth" -le 32 ] || { echo "MSIME launcher symlink chain is too deep: $0" >&2; exit 1; }
  link=$(readlink "$launcher_path")
  case "$link" in
    /*) launcher_path=$link ;;
    *) launcher_path=$(dirname -- "$launcher_path")/$link ;;
  esac
done
launcher_dir=$(CDPATH= cd -- "$(dirname -- "$launcher_path")" && pwd)
# An explicit override must fail visibly if invalid. Only an absent user configuration falls back to the system configuration supplied by IBus.
# Neither file existing is the one state that means first-run setup has not run yet; an override, an unreadable file or a dangling symlink is a broken configuration and gets no setup guidance.
not_configured=
if [ -n "${MSIME_IBUS_OPTIONS:-}" ]; then
  config=$MSIME_IBUS_OPTIONS
else
  config=${XDG_CONFIG_HOME:-$HOME/.config}/msime-client/runtime-options.json
  case "$config" in
    /*) ;;
    *) echo "MSIME user configuration directory must be absolute" >&2; exit 1 ;;
  esac
  if [ ! -e "$config" ] && [ ! -L "$config" ]; then
    config=${1:-/etc/msime-client/runtime-options.json}
    if [ ! -e "$config" ] && [ ! -L "$config" ]; then
      not_configured=1
    fi
  fi
fi
case "$config" in
  /*) ;;
  *)
    echo "MSIME runtime options must use an absolute path: $config" >&2
    exit 1
    ;;
esac
if [ ! -r "$config" ]; then
  echo "MSIME runtime options not found: $config" >&2
  # ibus-daemon shows nothing for a component that exits, so the user would see a dead input method. Open the first-run page instead; the guide limits itself to once per session because the daemon starts this launcher again on every selection.
  if [ -n "$not_configured" ] && [ -x "$launcher_dir/msime-linux-first-run-guide" ]; then
    "$launcher_dir/msime-linux-first-run-guide" --host ibus || :
  fi
  exit 1
fi
# Resolve both the launcher and options path before handing control to IBus; daemon working directories are not stable across desktop environments.
config_dir=$(CDPATH= cd -- "$(dirname -- "$config")" && pwd)
config="$config_dir/$(basename -- "$config")"

# ---- crash supervision ----
# ibus-daemon starts this launcher when the engine is selected and never starts it again when the component dies, so a crashed host would leave the user typing into nothing until they reselect the input source or restart IBus. Stay in front of msime-linux-ibus instead of exec'ing it and restart it after a crash, with the Windows watchdog's backoff (server/src/watchdog/main.cpp): the wait doubles from a 2 s floor to 30 s, and a host that ran for at least 30 s counts as healthy, so its crash waits 2 s again. A restarted host gets --recovered so it puts MSIME back on the focused context.
# Three endings are not crashes and are never restarted: the maintenance stop shortcut (stop_status, which must match msime_ibus_maintenance_stop_exit in src/core/ClientEngine.h); exit 0, which means the bus went away because ibus-daemon is exiting or restarting (after `ibus restart` the new daemon starts this launcher again once the engine is selected; after `ibus exit` nothing runs again), or that a restarted host found no bus at all; and a configuration that can no longer be read or a host program that is gone or no longer executable (the package was removed under a running host that then crashed), which a restart cannot fix.
# One ending is not a crash but is restarted: upgraded_status (msime_ibus_upgraded_exit) means a package upgrade replaced msime-linux-ibus and the host quit on a focus change with nothing composed so the new build can take over, the way the Windows installer starts the new IME after replacing it. That restart happens at once, still with --recovered, and leaves the backoff exactly as it was.
stop_status=77
upgraded_status=78
healthy_seconds=30
min_delay=2
max_delay=30
delay=0
child=
pause=
stopping=
# ibus-daemon stops a component with SIGTERM. Pass the request on as SIGTERM whatever arrived, because a background child of a non-interactive shell starts with SIGINT ignored.
request_stop() {
  stopping=1
  if [ -n "$child" ]; then kill -TERM "$child" 2>/dev/null || :; fi
  if [ -n "$pause" ]; then kill -TERM "$pause" 2>/dev/null || :; fi
}
trap request_stop TERM INT HUP
set -- "$config"
while :; do
  started=$(date +%s)
  "$launcher_dir/msime-linux-ibus" "$@" &
  child=$!
  # A signal that arrived before child was set found nothing to forward.
  if [ -n "$stopping" ]; then kill -TERM "$child" 2>/dev/null || :; fi
  status=0
  wait "$child" || status=$?
  # A trapped signal interrupts wait while the host is still shutting down; its real status comes from the next wait.
  while kill -0 "$child" 2>/dev/null; do
    status=0
    wait "$child" || status=$?
  done
  child=
  [ -z "$stopping" ] || exit "$status"
  case $status in
    0) exit 0 ;;
    "$stop_status") exit "$status" ;;
  esac
  # Checked before the backoff, so a removed package does not keep a launcher sleeping and retrying a file that is not there until ibus-daemon stops it.
  if [ ! -x "$launcher_dir/msime-linux-ibus" ]; then
    echo "msime-linux-ibus is no longer installed: $launcher_dir/msime-linux-ibus; not restarting" >&2
    exit 1
  fi
  if [ "$status" -eq "$upgraded_status" ]; then
    echo "msime-linux-ibus was replaced by an upgrade; starting the new build" >&2
  else
    if [ $(($(date +%s) - started)) -ge "$healthy_seconds" ]; then
      delay=$min_delay
    else
      delay=$((delay * 2))
      if [ "$delay" -lt "$min_delay" ]; then delay=$min_delay; fi
      if [ "$delay" -gt "$max_delay" ]; then delay=$max_delay; fi
    fi
    echo "msime-linux-ibus exited with status $status; restarting in ${delay}s" >&2
    sleep "$delay" &
    pause=$!
    if [ -n "$stopping" ]; then kill -TERM "$pause" 2>/dev/null || :; fi
    wait "$pause" || :
    pause=
    [ -z "$stopping" ] || exit "$status"
  fi
  if [ ! -r "$config" ]; then
    echo "MSIME runtime options are no longer readable: $config; not restarting" >&2
    exit 1
  fi
  set -- --recovered "$config"
done
