#!/bin/bash
# summary: Show the terminal greeting with system information.
# Always use our config: a person's fastfetch config can run commands or make network requests.
set -euo pipefail

usage() {
  cat <<'USAGE'
Usage: starchaser greeting [show|hook|on|off|status]
  show     Show the ship scene and this computer's details now.
  hook     Show in a new terminal; animate only the first eligible one per login.
  on|off   Turn the terminal greeting on or off for this account (default: on).
  status   Print on or off.
  -h, --help   Show this help.
USAGE
}

tmpfiles=()
cleanup() { if (( ${#tmpfiles[@]} )); then rm -f "${tmpfiles[@]}"; fi; }
trap cleanup EXIT
# Ctrl-C ends the scene (it restores the screen itself) without ending the shell that started us.
trap : INT
setting=${XDG_CONFIG_HOME:-$HOME/.config}/starchaser/greeting
enabled() {
  local value=on
  if [[ -f $setting ]]; then read -r value < "$setting" || true; fi
  [[ $value != off ]]
}
intro_path() {
  local here
  here=$(dirname "$(readlink -f "$0")")
  [[ -f $here/starchaser-intro ]] && echo "$here/starchaser-intro" || command -v starchaser 2>/dev/null
}
remote_shell() {
  [[ -n ${SSH_CONNECTION:-}${SSH_TTY:-}${SSH_CLIENT:-} ]]
}
motion_allowed() {
  [[ ${STARCHASER_SCREEN_READER_TERMINAL:-} != 1 ]] || return 1
  command -v python3 >/dev/null 2>&1 || return 1
  python3 - <<'MOTION'
import json, os, re
from pathlib import Path
config = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config")))
try:
    access = json.loads((config / "starchaser/accessibility.json").read_text())
except (OSError, ValueError):
    access = {}
try:
    speed = (config / "hypr/input.lua").read_text()
except OSError:
    speed = ""
raise SystemExit(1 if access.get("reduced_motion") or access.get("screen_reader") or
                 re.search(r"animation_speed\s*=\s*[\"']off[\"']", speed) else 0)
MOTION
}
claim_animation() {
  # The login launcher supplies a fresh token, even if another login keeps XDG_RUNTIME_DIR alive.
  # Fall back for sessions started without that launcher; without a session identity, stay still.
  local session=${STARCHASER_LOGIN_SESSION:-${HYPRLAND_INSTANCE_SIGNATURE:-${XDG_SESSION_ID:-}}}
  local runtime=${XDG_RUNTIME_DIR:-}
  [[ -n $session && -n $runtime && $session != *[!a-zA-Z0-9_.-]* ]] || return 1
  # Claim the directory with a direct creation call: some mkdir implementations
  # report success when a racing process created it, which would play the scene twice.
  python3 - "$runtime" "$session" <<'CLAIM'
import os, sys
from pathlib import Path
os.umask(0o077)
directory = Path(sys.argv[1]) / "starchaser-greeting"
try:
    directory.mkdir(parents=True, exist_ok=True)
    (directory / ("animation-" + sys.argv[2])).mkdir()
except OSError:
    raise SystemExit(1)
CLAIM
}
show() {
  command -v fastfetch >/dev/null 2>&1 || return 0
  local conf here
  here=$(dirname "$(readlink -f "$0")")
  conf=$here/../config/fastfetch
  [[ -f $conf/config.jsonc ]] || conf=/usr/share/starchaser/config/fastfetch
  [[ -f $conf/config.jsonc ]] || return 0
  local columns=${COLUMNS:-} rows=${LINES:-} size config=$conf/config.jsonc room logo=yes compact="" status=0
  # A non-interactive script does not see COLUMNS, so ask the terminal; assume a wide one if nothing answers.
  if [[ ! $columns =~ ^[1-9][0-9]{0,3}$ ]]; then
    size=$({ stty size </dev/tty; } 2>/dev/null) || size=
    columns=${size#* }
  fi
  [[ $columns =~ ^[1-9][0-9]{0,3}$ ]] || columns=$(tput cols 2>/dev/null) || columns=
  [[ $columns =~ ^[1-9][0-9]{0,3}$ ]] || columns=100
  # The height the same way (LINES, then the terminal; tput guesses 24 with no terminal). Unknown means tall enough.
  if [[ ! $rows =~ ^[1-9][0-9]{0,3}$ ]]; then
    size=$({ stty size </dev/tty; } 2>/dev/null) || size=
    rows=${size%% *}
  fi
  # Under 28 rows the ship scene would push the top lines off the screen: show the details alone.
  if [[ $rows =~ ^[1-9][0-9]{0,3}$ ]] && (( rows < 28 )); then logo=no; fi
  if (( columns < 90 )); then
    # Narrower than the full layout: shorten each value to the room left after the ship (31) and the key (13),
    # or drop the ship below 60 columns, so no line wraps over the logo.
    if (( columns < 60 )); then logo=no; room=$((columns - 14)); else room=$((columns - 45)); fi
    (( room >= 8 )) || room=8
    (( room <= 40 )) || room=40
    # fastfetch has no command-line option for a module's format, so write a copy sized to this terminal.
    config=$conf/config-compact.jsonc
    if compact=$(mktemp --suffix=.jsonc 2>/dev/null); then
      tmpfiles+=("$compact")
      if sed "s/:16}/:$room}/g; s/:-16}/:-$room}/g" "$config" > "$compact" 2>/dev/null; then config=$compact; fi
    fi
  fi
  # The native release is longer than the old 16-column value. Keep it whole when the terminal has room.
  # Arch releases retain their existing formatting; never disguise the kernel that is actually running.
  local release native_config
  release=$(uname -r)
  if [[ $release =~ ^[0-9]+(\.[0-9]+)+-(Starchaser(-LTS)?|starchaser(-lts)?[0-9]+)$ ]] && (( columns >= 90 )); then
    if native_config=$(mktemp --suffix=.jsonc 2>/dev/null); then
      tmpfiles+=("$native_config")
      if sed 's/{release:-16}/{release}/g' "$config" > "$native_config" 2>/dev/null; then config=$native_config; fi
    fi
  fi
  # the screen reader's terminal (bin/starchaser-terminal) never shows its program's name: "Terminal  Screen reader"
  local reader_config
  if [[ ${STARCHASER_SCREEN_READER_TERMINAL:-} = 1 ]] && reader_config=$(mktemp --suffix=.jsonc 2>/dev/null); then
    tmpfiles+=("$reader_config")
    if sed '/"type": "terminal"/,/}/ s/"format": "[^"]*"/"format": "Screen reader"/' "$config" > "$reader_config" 2>/dev/null; then
      config=$reader_config
    fi
  fi
  local intro rest="" output="" lines place
  intro=$(intro_path) || intro=
  if [[ $logo = yes && -n $intro ]] && command -v python3 >/dev/null 2>&1; then
    rest=$(mktemp 2>/dev/null) && tmpfiles+=("$rest") || rest=
    # The resting frame is the logo. If it cannot be made, show the details alone.
    if [[ -n $rest ]] && ! python3 "$intro" rest > "$rest" 2>/dev/null; then rest=; fi
  fi
  if [[ -z $rest ]]; then
    fastfetch -c "$config" --logo none || status=$?
    return "$status"
  fi
  # The details appear at once beside the resting frame; then the scene plays over that same frame, in place,
  # for people at a real terminal who are not connected remotely. From the shell hook it plays beside the prompt.
  if [[ -t 0 && -t 1 && ${TERM:-dumb} != dumb && -z ${STARCHASER_GREETING_STATIC:-} ]] && ! remote_shell && motion_allowed; then
    output=$(mktemp 2>/dev/null) && tmpfiles+=("$output") || output=
  fi
  if [[ -z $output ]]; then
    fastfetch -c "$config" --file-raw "$rest" || status=$?
    return "$status"
  fi
  fastfetch -c "$config" --file-raw "$rest" --pipe false > "$output" || status=$?
  cat "$output"
  lines=$(wc -l < "$output")
  (( status == 0 && lines > 0 )) || return "$status"
  # Moving up cannot reach lines that scrolled away: a short window gets the resting frame only.
  size=$(stty size 2>/dev/null) || size=
  [[ ${rows:-} =~ ^[1-9][0-9]*$ ]] || rows=${size%% *}
  [[ $rows =~ ^[0-9]+$ ]] && (( lines < rows )) || return "$status"
  # The logo starts on the first line and 3 columns in (the config pads it 2 columns from the left).
  if [[ -n ${STARCHASER_GREETING_PLAY_FD:-} ]]; then
    # The shell snippet starts the scene once this returns, at the place the terminal reports, and stops it before
    # the first command runs. A window without room for that gets the resting frame only.
    place=$(python3 "$intro" locate "$output" --col 3) || return "$status"
    # Only an eligible terminal can spend this login's animation; locate can decline even after the height check.
    if [[ ${greeting_hook:-0} = 1 ]] && ! claim_animation; then return "$status"; fi
    { printf '%s\n' "$place" >&"$STARCHASER_GREETING_PLAY_FD"; } 2>/dev/null || true
    return "$status"
  fi
  python3 "$intro" play --up "$lines" --col 3 || true
  return "$status"
}
hook() {
  # A child process cannot read the calling shell's $-. Only the guarded shell snippet sets this flag.
  [[ ${STARCHASER_GREETING_INTERACTIVE:-} = 1 && -t 1 && ${TERM:-dumb} != dumb ]] || return 0
  remote_shell && return 0
  [[ ! -v CLAUDECODE ]] || return 0
  local name terminal runtime session shown screen_pid screen_start
  for name in "${!CLAUDE_CODE_@}" "${!STARCHASER_AGENT@}"; do
    [[ -z $name ]] || return 0
  done
  enabled || return 0
  { terminal=$(tty <&3); } 3<&1 || return 0
  [[ ${STARCHASER_GREETING_TERMINAL:-} != "$terminal" ]] || return 0
  command -v fastfetch >/dev/null 2>&1 || return 0

  if [[ -n ${TMUX:-}${STY:-} ]]; then
    runtime=${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/starchaser}/starchaser-greeting
    (umask 077 && mkdir -p "$runtime") || return 0
    # The lock covers checking and claiming a session, including two panes starting together.
    exec 9>"$runtime/session.lock"
    flock 9 || return 0
    if [[ -n ${TMUX:-} ]]; then
      session=$(tmux display-message -p '#{session_id}' 2>/dev/null) || return 0
      shown=$(tmux show-environment -t "$session" STARCHASER_GREETING_SHOWN 2>/dev/null) || shown=
      [[ $shown != STARCHASER_GREETING_SHOWN=1 ]] || return 0
      tmux set-environment -t "$session" STARCHASER_GREETING_SHOWN 1 2>/dev/null || return 0
    else
      # The server's start time keeps a reused screen PID from suppressing a future session.
      screen_pid=${STY%%.*}
      [[ $screen_pid =~ ^[0-9]+$ ]] || return 0
      screen_start=$(awk '{print $22}' "/proc/$screen_pid/stat" 2>/dev/null) || return 0
      mkdir "$runtime/screen-${STY//[^a-zA-Z0-9_.-]/_}-$screen_start" 2>/dev/null || return 0
    fi
    flock -u 9
    exec 9>&-
  fi
  # kitty counts a window as "running a program" until the shell shows its first prompt, and this startup
  # hook runs before that, so closing the window during the greeting asked about "python3". Tell kitty
  # we are at a prompt (the same OSC 133 mark its shell integration sends); the real prompt marks itself again.
  if [[ -n ${KITTY_WINDOW_ID:-} && ${KITTY_SHELL_INTEGRATION:-} != *no-prompt-mark* ]]; then printf '\033]133;A\007'; fi
  # Only the shell snippet can play the scene beside the prompt (it passes STARCHASER_GREETING_PLAY_FD to learn
  # the scene's place); without it the resting frame stays still, so the prompt never waits for the scene.
  [[ ${STARCHASER_GREETING_PLAY_FD:-} =~ ^[1-9][0-9]*$ ]] || STARCHASER_GREETING_STATIC=1
  local greeting_hook=1
  show
}
scene() {
  # Recheck after the hook returns in case reduced motion changed while locating the logo.
  motion_allowed || return 0
  # The shell snippet runs this in the background with the options `locate` printed.
  local intro arg
  for arg in "$@"; do [[ $arg =~ ^(--(top|col|width|size)|[0-9]+(x[0-9]+)?)$ ]] || exit 2; done
  intro=$(intro_path) || exit 0
  exec python3 "$intro" play "$@"
}

for x in "$@"; do case $x in -h|--help) usage; exit 0 ;; esac; done   # help after a command word too (r172)
[[ $# -le 1 || $1 = scene ]] || { echo "starchaser greeting: it takes one command at a time, not '$*'. Run 'starchaser greeting --help' for more help." >&2; usage >&2; exit 2; }
case ${1:-show} in
  -h|--help|help) usage ;;
  show) show ;;
  hook) hook ;;
  scene) shift; scene "$@" ;;
  status) if enabled; then echo on; else echo off; fi ;;
  on|off)
    temp="$setting.$$.tmp"
    tmpfiles+=("$temp")
    if ! reason=$({ mkdir -p "${setting%/*}" && printf '%s\n' "$1" > "$temp" && sync -f "$temp" && mv -f "$temp" "$setting"; } 2>&1); then
      echo "starchaser greeting: couldn't save the setting (${reason##*: }). Check that you can write to ~/.config." >&2
      exit 1
    fi
    # One plain line for a person at a terminal; Settings and scripts read the status back and see no change.
    if [[ -t 1 ]]; then echo "Terminal greeting is $1."; fi
    ;;
  *) echo "starchaser greeting: unknown command '$1'. Run 'starchaser greeting --help' for more help." >&2; usage >&2; exit 2 ;;
esac
