#!/bin/sh
# 00 for Linux: opens the 00rg picker. stage.sh ships this file as bin/00 in a linux package.
# Linux has no global Ctrl Ctrl: under Wayland no app may watch the keyboard (Daniel #7417, nova #7419).
# So this command is the way in: the app menu entries install.sh writes ("00", and one per product:
# "0neo" runs 00 --pick Neomonic, "0vc" runs 00 --pick "Version Control"; Daniel #7420), typing 00
# in a terminal, or a desktop shortcut the user binds to the 00 command.
# Linux has no native picker window yet, so the picker is 0gui's shell in the default browser.
#
# usage: 00 [--resident | --pick LABEL]
#   (none)        start 0gui if it is not running, then open its shell page
#   --resident    only start 0gui and exit (the login autostart entry runs this)
#   --pick LABEL  open the picker row LABEL straight away, read from the <member> lines in ../00.d
#                 (comments skipped). A url row opens in the browser, after starting its server= if
#                 it has one. An exe row runs bin/<exe>; with console="new" it gets a terminal window
#                 (this one when 00 runs in a terminal). requires="X" must be an installed bin/X.
# env: OORG_OPEN=CMD opens the page instead of xdg-open (tests).
#      OORG_TERM=CMD runs a console row as: CMD <exe path> (default: the first of x-terminal-emulator,
#      gnome-terminal, konsole, xfce4-terminal, xterm).
# 0gui's output goes to ${XDG_STATE_HOME:-~/.local/state}/00rg/0gui.log.
# exit: 0 ok. 1 0gui did not come up, no way to open a browser or terminal, no such row, or the row's
#   program is missing. 2 bad arguments.
set -eu

PORT=9994
URL=http://127.0.0.1:$PORT/ui/shell.html
# The command is a symlink in /usr/local/bin; 0gui sits beside the real file.
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
BIN=$(cd "$(dirname "$SELF")" && pwd)

usage() { echo "usage: 00 [--resident | --pick LABEL]" >&2; exit 2; }
RESIDENT=0
PICK=
case ${1:-} in
    '') [ $# -eq 0 ] || usage ;;
    --resident) [ $# -eq 1 ] || usage; RESIDENT=1 ;;
    --pick) [ $# -eq 2 ] && [ -n "$2" ] || usage; PICK=$2 ;;
    *) usage ;;
esac

# up: the page at $URL answers. With no curl or wget there is no probe: start 0gui anyway
# (a second one only fails to bind) and give it a second.
PROBE=
if command -v curl >/dev/null 2>&1; then PROBE=curl; elif command -v wget >/dev/null 2>&1; then PROBE=wget; fi
up() {
    case $PROBE in
        curl) curl -fs -o /dev/null --max-time 1 "$URL" ;;
        wget) wget -q -T 1 -O /dev/null "$URL" ;;
        *) return 1 ;;
    esac
}

# start_gui: start bin/0gui serve unless $URL already answers, and wait for it.
start_gui() {
    up && return 0
    [ -x "$BIN/0gui" ] || { echo "00: $BIN/0gui is missing" >&2; exit 1; }
    LOGDIR=${XDG_STATE_HOME:-$HOME/.local/state}/00rg
    mkdir -p "$LOGDIR"
    nohup "$BIN/0gui" serve >> "$LOGDIR/0gui.log" 2>&1 &
    n=0
    [ -n "$PROBE" ] || { sleep 1; n=20; }
    while [ "$n" -lt 20 ] && ! up; do
        n=$((n + 1))
        if [ "$n" -ge 20 ]; then
            echo "00: 0gui did not answer on port $PORT; see $LOGDIR/0gui.log" >&2
            exit 1
        fi
        sleep 0.25 2>/dev/null || sleep 1
    done
}

open_url() {
    if [ -n "${OORG_OPEN:-}" ]; then
        exec $OORG_OPEN "$1"
    elif command -v xdg-open >/dev/null 2>&1; then
        exec xdg-open "$1"
    elif command -v gio >/dev/null 2>&1; then
        exec gio open "$1"
    fi
    echo "00: no xdg-open or gio here; open $1 in a browser" >&2
    exit 1
}

if [ -z "$PICK" ]; then
    start_gui
    [ "$RESIDENT" -eq 1 ] && exit 0
    open_url "$URL"
fi

# --pick: the member rows of every 00.d file, comments cut out (a row can be switched off by
# moving it inside <!-- -->), one tag per line as the files write them.
D00=$BIN/../00.d
rows() {
    for x in "$D00"/*.xml; do
        [ -f "$x" ] || continue
        awk '{ s = s $0 "\n" }
            END {
                while ((i = index(s, "<!--")) > 0) {
                    j = index(substr(s, i), "-->")
                    if (j == 0) { s = substr(s, 1, i - 1); break }
                    s = substr(s, 1, i - 1) substr(s, i + j + 2)
                }
                printf "%s", s
            }' "$x"
    done
}
# attr TAG NAME: the value of NAME="..." in TAG.
attr() { printf '%s\n' "$1" | sed -n "s/.*[[:space:]]$2=\"\([^\"]*\)\".*/\1/p"; }

ROW=
while IFS= read -r line; do
    case $line in *"<member "*) ;; *) continue ;; esac
    if [ "$(attr "$line" label)" = "$PICK" ]; then ROW=$line; break; fi
done <<ROWS
$(rows)
ROWS
[ -n "$ROW" ] || { echo "00: no picker row '$PICK' in $D00" >&2; exit 1; }

REQ=$(attr "$ROW" requires)
if [ -n "$REQ" ] && [ ! -x "$BIN/$REQ" ]; then
    echo "00: '$PICK' needs $REQ, which is not installed ($BIN/$REQ)" >&2
    exit 1
fi

MURL=$(attr "$ROW" url)
EXE=$(attr "$ROW" exe)
if [ -n "$MURL" ]; then
    # Only 0gui is a server today (every 00.d <server> line names it); start it for its rows.
    if [ "$(attr "$ROW" server)" = 0gui ]; then
        URL=$MURL
        start_gui
    fi
    open_url "$MURL"
fi
[ -n "$EXE" ] || { echo "00: picker row '$PICK' has no url and no exe" >&2; exit 1; }
case $EXE in */*|.*) echo "00: picker row '$PICK' has a bad exe '$EXE'" >&2; exit 1 ;; esac
[ -x "$BIN/$EXE" ] || { echo "00: $BIN/$EXE is missing" >&2; exit 1; }
if [ "$(attr "$ROW" console)" != new ] || { [ -t 0 ] && [ -t 1 ]; }; then
    exec "$BIN/$EXE"
fi
if [ -n "${OORG_TERM:-}" ]; then
    exec $OORG_TERM "$BIN/$EXE"
elif command -v x-terminal-emulator >/dev/null 2>&1; then
    exec x-terminal-emulator -e "$BIN/$EXE"
elif command -v gnome-terminal >/dev/null 2>&1; then
    exec gnome-terminal -- "$BIN/$EXE"
elif command -v konsole >/dev/null 2>&1; then
    exec konsole -e "$BIN/$EXE"
elif command -v xfce4-terminal >/dev/null 2>&1; then
    exec xfce4-terminal -x "$BIN/$EXE"
elif command -v xterm >/dev/null 2>&1; then
    exec xterm -e "$BIN/$EXE"
fi
echo "00: no terminal program here to run $EXE in; run $BIN/$EXE from a terminal" >&2
exit 1
