#!/usr/bin/env sh
# oosh install bootstrap — POSIX `sh`, shared by three delivery paths:
#
#   1. Curl one-liner       bash -c "$(curl .../init/oosh)"
#   2. ossh install <host>  SCPs this file to remote and runs `./oosh mode root …`
#   3. Drag-and-drop        double-click Install-oosh.command (it invokes ./init/oosh)
#
# All three converge on `ossh install.continue.local` (ossh:476) — the
# mature state-machine entrypoint. This file's only job is: check
# prereqs, resolve branch, clone if needed, move to ~/oosh, hand off.
#
# Prereqs:
#   bash 4+   macOS: brew install bash        Debian/RHEL: already there       Alpine: apk add bash
#   git       macOS: xcode-select --install   Debian:      apt install git     Alpine: apk add git
#
# On Alpine, `ossh prereqs.install <host>` from a controlling laptop also
# installs `shadow` (useradd/chpasswd) and `util-linux` (runuser); these
# aren't strictly oosh runtime prereqs, but `os platform.test` needs them
# for its 4-user user-switching flow. See docs/ossh.md.

die() { echo "oosh install: $*" >&2; exit 1; }

# ─── Auto-run guard ──────────────────────────────────────────────────────
# Sourcing this file (e.g. test/test.oosh) must NOT fire the installer
# below — sudo re-exec, `mv $OOSH_DIR $HOME/oosh`, and state-machine
# handoff have wiped user oosh trees in the past. Either opt-out works:
# BASH_SOURCE[0] != $0 (sourced) or OOSH_NO_AUTORUN=1 (eval-strip loaders
# that defeat BASH_SOURCE detection). `set -e` lives below the guard so
# errexit doesn't leak into the sourcing shell.
#
# NB: this check runs BEFORE the POSIX prelude so the prelude never runs
# when sourced. Under bash, accessing BASH_SOURCE as a scalar yields the
# top-frame source path (== element 0). Under dash/ash, BASH_SOURCE is
# unset and `${BASH_SOURCE:-$0}` defaults to `$0`. We deliberately do NOT
# use `${BASH_SOURCE[0]:-$0}` because the `[0]` subscript triggers
# "Bad substitution" at runtime under POSIX shells. So under POSIX sh the
# sourcing-detection no-ops, and OOSH_NO_AUTORUN=1 is the reliable escape.
if [ "${BASH_SOURCE:-$0}" != "$0" ] || [ "${OOSH_NO_AUTORUN:-0}" = "1" ]; then
  return 0 2>/dev/null || exit 0
fi

# ─── Branch default ──────────────────────────────────────────────────────
# Resolved early — the self-re-exec block below needs $OOSH_BRANCH for
# the curl-pipe pre-clone fallback. `promote` rewrites this literal
# (see private.promote.rewrite.self.branch in promote:430). Set BEFORE
# the POSIX prelude so prelude install steps that need a branch (the
# bash-re-exec pre-clone) can read it.
OOSH_SELF_BRANCH="${OOSH_SELF_BRANCH:-testing}"
: ${OOSH_BRANCH:=$OOSH_SELF_BRANCH}

# ═══════════════════════════════════════════════════════════════════════════
# Phase A — self-install platform deps (POSIX `sh`)
# ═══════════════════════════════════════════════════════════════════════════
# Runs under whatever sh the host provides — bash 3.2 on macOS,
# dash on Debian, ash on Alpine, busybox on naked containers. Goal:
# ensure git + bash 4+ exist on PATH so Phase B's prereq check passes
# and downstream framework scripts (ossh, oo, state, this) — which DO
# require bash 4+ — find what they need.
#
# Why here and not in `ossh prereqs.install`: this script needs to be a
# self-contained drag-and-drop bootstrap. The historical main-branch
# init/oosh did this; an interim refactor moved install logic to
# ossh.prereqs.install (which only works AFTER oosh is installed somewhere
# with ssh access). We restore the self-install promise here and reduce
# ossh.prereqs.install to a thin SCP+run wrapper around this file.
#
# `set -e` is intentionally NOT enabled until Phase B — install commands
# may have non-zero exits we want to handle gracefully here.

# SUDO setup. Match the contract `this:60-66` uses post-install: empty when
# already root, "sudo" otherwise. Distinguish unset vs. empty with ${SUDO+x}
# — root may set SUDO="" intentionally and we must not clobber that.
if [ -z "${SUDO+x}" ]; then
  if [ "$(id -u 2>/dev/null)" = "0" ]; then
    SUDO=""
  else
    SUDO="sudo"
  fi
fi
export SUDO

# PM detection — POSIX port of the historical PM-discovery helper, extended
# with the same choice strings ossh.pm.discover uses (ossh:2128-2140). Sets
# OOSH_PM_BIN (the binary name), OOSH_PM (full install command), and
# OOSH_PM_UPDATE (apt-get update or empty).
oosh_pm_detect() {
  for _pm in brew apt-get dnf yum apk pacman pkg; do
    if command -v "$_pm" >/dev/null 2>&1; then
      OOSH_PM_BIN="$_pm"
      OOSH_PM_UPDATE=""
      case "$_pm" in
        brew)    OOSH_PM="brew install" ;;
        apt-get) OOSH_PM="apt-get -y install"; OOSH_PM_UPDATE="apt-get update" ;;
        dnf)     OOSH_PM="dnf -y install" ;;
        yum)     OOSH_PM="yum -y install" ;;
        apk)     OOSH_PM="apk add" ;;
        pacman)  OOSH_PM="pacman -S --noconfirm" ;;
        pkg)     OOSH_PM="pkg install -y" ;;
      esac
      export OOSH_PM OOSH_PM_BIN OOSH_PM_UPDATE
      return 0
    fi
  done
  return 1
}

# Install <cmd> (optionally with explicit <pkg> name) via the detected PM,
# idempotent. Skips if cmd already present. Returns 1 if no PM available
# OR install failed.
oosh_cmd_install() {
  _cmd="$1"; _pkg="${2:-$1}"
  if command -v "$_cmd" >/dev/null 2>&1; then
    return 0
  fi
  if [ -z "$OOSH_PM" ]; then
    return 1
  fi
  echo "oosh install: installing $_pkg via '$OOSH_PM'…" >&2
  # Homebrew refuses to run as root (and refuses sudo'd invocations).
  # macOS prelude phase: caller is the original non-root user (admin),
  # so $SUDO is "sudo " — but `sudo brew install` makes brew see euid=0
  # and fails with "Running Homebrew as root is extremely dangerous".
  # Drop $SUDO for brew specifically. For all other PMs (apt-get, dnf,
  # apk, pkg) the package install needs root and $SUDO is correct.
  if [ "$OOSH_PM_BIN" = "brew" ]; then
    if [ "$(id -u)" = "0" ] && [ -n "$SUDO_USER" ]; then
      # Phase-B side (post-sudo-reexec): drop back to the original user
      # via login shell so brew finds itself on PATH (paths.d setup).
      sudo -u "$SUDO_USER" -H bash -lc "$OOSH_PM '$_pkg'"
    else
      $OOSH_PM "$_pkg"
    fi
  else
    $SUDO $OOSH_PM "$_pkg"
  fi
}

# Probe whether bash >= 4 is on PATH. POSIX-friendly; uses `bash --version`
# and parses the major version digit. Returns 0 iff bash 4+ found.
oosh_bash_ok() {
  command -v bash >/dev/null 2>&1 || return 1
  _bv="$(bash --version 2>/dev/null | head -1)"
  case "$_bv" in
    *'version 4.'*|*'version 5.'*|*'version 6.'*|*'version 7.'*|*'version 8.'*|*'version 9.'*) return 0 ;;
  esac
  return 1
}

# ─── 1. PM detection (with macOS Homebrew bootstrap fallback) ────────────
if ! oosh_pm_detect; then
  if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
    echo "oosh install: bootstrapping Homebrew on macOS (no PM detected) — this may take several minutes…" >&2
    NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" \
      || die "Homebrew bootstrap failed"
    # Right after install brew isn't on PATH yet — probe canonical locations
    # and source `brew shellenv` so subsequent `command -v brew` succeeds.
    if [ -x /opt/homebrew/bin/brew ]; then
      eval "$(/opt/homebrew/bin/brew shellenv)"
    elif [ -x /usr/local/bin/brew ]; then
      eval "$(/usr/local/bin/brew shellenv)"
    fi
    oosh_pm_detect || die "Homebrew bootstrap reported success but brew binary not found at /opt/homebrew/bin or /usr/local/bin"
  fi
  # Linux + no PM is pathological (every supported distro ships a PM by
  # default). Fall through; the bash-phase prereq check will produce the
  # framed error if git or bash are also missing.
fi

# ─── 2. apt-get update (gated, one-shot) ────────────────────────────────
# Required on freshly-pulled apt images (cached repo metadata may be empty)
# before the first install. Gate via OOSH_APT_UPDATED so re-exec'd children
# skip the second invocation. Cheap no-op once metadata is fresh.
#
# Output is suppressed (50 MB of "Get:" lines isn't useful), but a status
# line tells the user what's happening — without it, slow mirrors give
# 30–60s of zero output that looks identical to a hang.
if [ "$OOSH_PM_BIN" = "apt-get" ] && [ -z "$OOSH_APT_UPDATED" ]; then
  echo "oosh install: refreshing package lists (apt-get update) — this may take 30-60 seconds…" >&2
  $SUDO apt-get update >/dev/null 2>&1 || true
  export OOSH_APT_UPDATED=1
fi

# ─── 3. Install git BEFORE any bash re-exec ──────────────────────────────
# The bash 4+ re-exec block below (lines 58-75 in the pre-prelude file,
# now shifted) does `git clone` to a temp dir when $0 isn't a file
# (curl-pipe / drag-and-drop case where $0 == "bash"). Same in the sudo
# re-exec block. So git must exist before either re-exec point can run.
oosh_cmd_install git || true

# ─── 4. Install bash 4+ if missing ───────────────────────────────────────
if ! oosh_bash_ok; then
  if [ "$OOSH_PM_BIN" = "brew" ]; then
    # macOS: install brew bash + wire /etc/paths.d so non-interactive ssh
    # sessions actually find it (port of ossh.prereqs.install:2251-2277).
    # `command -v bash` would short-circuit because /bin/bash 3.2 is always
    # present, so use the brew-prefix probe instead.
    if [ ! -x /opt/homebrew/bin/bash ] && [ ! -x /usr/local/bin/bash ]; then
      brew install bash || die "brew install bash failed"
    fi
    if [ -x /opt/homebrew/bin/bash ]; then
      _newbash=/opt/homebrew/bin/bash
    elif [ -x /usr/local/bin/bash ]; then
      _newbash=/usr/local/bin/bash
    else
      die "brew install bash reported success but binary not found at /opt/homebrew/bin or /usr/local/bin"
    fi
    # Wire paths.d once so future ssh-non-interactive sessions also find
    # brew bash via path_helper. Best-effort — sudo prompt is OK here.
    if [ ! -f /etc/paths.d/oosh-homebrew ]; then
      echo "$(dirname "$_newbash")" | $SUDO tee /etc/paths.d/oosh-homebrew >/dev/null \
        && $SUDO chmod 644 /etc/paths.d/oosh-homebrew \
        || echo "oosh install: WARN — could not wire /etc/paths.d/oosh-homebrew (non-interactive ssh may not find brew bash)" >&2
    fi
    # Hand off to Phase B under the new bash. Pre-clone if $0 isn't a real
    # file (curl-pipe / .command).
    if [ -f "$0" ]; then
      exec "$_newbash" "$0" "$@"
    else
      _tmp="$(mktemp -d)"
      _repo="${OOSH_REPO:-https://github.com/Cerulean-Circle-GmbH/once.sh.git}"
      echo "oosh install: pre-cloning $_repo @ $OOSH_BRANCH to $_tmp for bash re-exec…" >&2
      git clone -b "$OOSH_BRANCH" "$_repo" "$_tmp/once.sh" >/dev/null 2>&1 \
        || die "pre-re-exec clone failed (network issue?)"
      exec "$_newbash" "$_tmp/once.sh/init/oosh" "$@"
    fi
  elif [ -n "$OOSH_PM" ]; then
    # Linux: install bash via the PM. After install the existing bash
    # `BASH_VERSINFO` check in Phase B will pass (the running shell's bash
    # version is unchanged by an install, but on Linux the running shell
    # is already bash 4+ from `bash -c "$(curl …)"`'s default — this branch
    # only fires on weird hosts that explicitly invoke us under sh+old-bash).
    oosh_cmd_install bash || die "$OOSH_PM bash failed"
  fi
  # else: no PM found — fall through; framed error in Phase B.
fi

# Phase A is complete. init/oosh now runs end-to-end under whatever sh
# the host provides; no bash re-exec needed. Bash 4+ availability is
# enforced by the framed prereq check below — we don't `die` here so
# the rich error block can show install hints.

# ═══════════════════════════════════════════════════════════════════════════
# Phase B — POSIX `sh` install logic
# ═══════════════════════════════════════════════════════════════════════════

set -e

# Newline literal for string-accumulator pattern (POSIX equivalent of
# bash arrays). Used by _oosh_missing / _oosh_hints below.
NL='
'

# ─── Ensure bash 4+ is on PATH for downstream consumers ─────────────────
# init/oosh runs under sh, but the framework (ossh, oo, state, this) needs
# bash 4+. macOS ships /bin/bash 3.2 — Phase A's prelude installs brew bash,
# but ssh non-login non-interactive sessions on macOS get
# PATH=/usr/bin:/bin:/usr/sbin:/sbin from launchd; `/etc/paths.d/*` is only
# consumed by `path_helper`, which only runs from /etc/profile family.
# Prepend brew bash dir if found so downstream `#!/usr/bin/env bash`
# shebangs resolve to bash 4+. No re-exec needed (init/oosh is sh).
for _bashCandidate in /opt/homebrew/bin /usr/local/bin; do
  if [ -x "$_bashCandidate/bash" ]; then
    case ":$PATH:" in
      *":$_bashCandidate:"*) ;;
      *) export PATH="$_bashCandidate:$PATH" ;;
    esac
    break
  fi
done
unset _bashCandidate

# Also prepend the directory of whatever bash is currently on PATH —
# preserves the historical guarantee that `command -v bash` at
# this:801/this:927 picks bash 4+ even when the inherited PATH put a
# stale bash earlier. If no bash is on PATH at all, the prereq check
# below produces the framed error.
_currentBashDir="$(command -v bash 2>/dev/null)"
if [ -n "$_currentBashDir" ]; then
  _currentBashDir="$(dirname "$_currentBashDir")"
  if [ -n "$_currentBashDir" ] && [ "$_currentBashDir" != "." ]; then
    case ":$PATH:" in
      *":$_currentBashDir:"*) ;;
      *) export PATH="$_currentBashDir:$PATH" ;;
    esac
  fi
fi
unset _currentBashDir

# ─── Arg parsing ─────────────────────────────────────────────────────────
# `ossh install` invokes us as:
#   ./oosh mode root <sshHost> <configRemote|_> <branch> <logLevel>
# Default path (curl one-liner / drag-and-drop) takes no args.
MODE=""
REMOTE_SSH_HOST=""
CONFIG_REMOTE=""
LOG_LEVEL_ARG=""
if [ "$1" = "mode" ]; then
  shift
  [ "$1" = "root" ] || die "only 'mode root' is supported (got '$1')"
  MODE=root; shift
  REMOTE_SSH_HOST="${1:-}";   [ -n "$1" ] && shift
  CONFIG_REMOTE="${1:-}";     [ -n "$1" ] && shift
  [ "$CONFIG_REMOTE" = "_" ] && CONFIG_REMOTE=""
  [ -n "$1" ] && OOSH_BRANCH="$1" && shift
  [ -n "$1" ] && LOG_LEVEL_ARG="$1" && shift
fi

# Sanitise branch (same strip chain as the old init/oosh; inlined because
# at this point `this.git.branch.short` isn't sourceable yet)
OOSH_BRANCH="${OOSH_BRANCH#refs/heads/}"
OOSH_BRANCH="${OOSH_BRANCH#refs/remotes/origin/}"
OOSH_BRANCH="${OOSH_BRANCH#heads/origin/}"
OOSH_BRANCH="${OOSH_BRANCH#origin/}"
export OOSH_BRANCH

# ─── Prereqs (essentials only) ────────────────────────────────────────────
# Phase A's POSIX prelude already installed git + bash 4+ via the platform
# PM (or bootstrapped Homebrew on naked macOS). All OTHER runtime prereqs
# (rsync, tree, etc.) install POST-clone via `ossh prereqs.install` (local
# mode) or lazily via `oo cmd <pkg>` at use-sites — that's the OOSH-canonical
# install primitive. init/oosh's only job is to get us TO the clone.
#
# Three things still need to be present to make it past the clone+handoff:
#   git    — to clone the repo
#   bash 4+ — every framework script (#!/usr/bin/env bash) requires it
#   sudo   — only when invoked non-root (we re-exec via sudo below)
# If any of these is missing AFTER Phase A, fail fast with a hint pointing
# at the canonical fix.
if ! command -v git >/dev/null 2>&1; then
  die "git missing after PM install attempt — install manually then re-run (apt/dnf/apk/brew install git)"
fi
if ! oosh_bash_ok; then
  die "bash 4+ missing after PM install attempt — install manually then re-run (brew install bash on macOS; apt/dnf/apk install bash on Linux)"
fi
if [ "$(id -u)" -ne 0 ] && [ -z "$MODE" ] && ! command -v sudo >/dev/null 2>&1; then
  die "sudo missing for non-root install — install manually as root then re-run, or run this installer as root directly"
fi

# ─── Non-root → sudo re-exec ─────────────────────────────────────────────
# Covers three invocation patterns in one guard:
#   1. Curl / drag-and-drop as non-root  (MODE empty, id -u != 0)
#   2. ossh install <host> with Host's User=non-root  (MODE=root, id -u != 0)
#   3. ossh install <host> with Host's User=root      (MODE=root, id -u == 0) — skipped
# i.e. we only need to re-exec when we're not already root. MODE=root is
# the SCP-handoff signal, orthogonal to whether sudo is needed.
if [ "$(id -u)" -ne 0 ]; then
  echo "oosh install: re-executing as root via sudo (enter password if prompted)…"
  # When curl-piped (`bash -c "$(curl …)"`), $0 is the literal string
  # "bash" (the shell's name), not a filesystem path — `sudo bash "$0"`
  # would become `sudo bash bash`, which bash resolves via PATH to
  # /usr/bin/bash and fails "cannot execute binary file." Pre-clone the
  # repo to a temp dir so we have a real init/oosh file to hand to sudo.
  # The re-exec'd init/oosh then moves the clone to $HOME/oosh via its
  # existing canonical-location logic.
  if [ ! -f "$0" ]; then
    _oosh_tmp_clone="$(mktemp -d)"
    REPO="${OOSH_REPO:-https://github.com/Cerulean-Circle-GmbH/once.sh.git}"
    echo "Pre-cloning $REPO (branch=$OOSH_BRANCH) into $_oosh_tmp_clone …"
    git clone -b "$OOSH_BRANCH" "$REPO" "$_oosh_tmp_clone/once.sh" >/dev/null 2>&1 \
      || die "pre-sudo clone failed (network issue?)"
    exec sudo -H -E sh "$_oosh_tmp_clone/once.sh/init/oosh" "$@"
  fi
  exec sudo -H -E sh "$0" "$@"
fi

# Alpine: /bin/su → /bin/busybox; busybox-su needs the binary suid for
# non-root identity switches (else `user login <user>` fails post-install
# with "must be suid to work properly"). Naked alpine ships busybox at
# 0755; real deployments ship suid. Soft-fail on any error.
# Mirrors ossh.prereqs.install for the caller-driven path.
if command -v apk >/dev/null 2>&1 && [ -e /bin/busybox ]; then
  chmod u+s /bin/busybox 2>/dev/null || true
fi

# ─── Resolve OOSH_DIR (where the repo lives or will live) ───────────────
OOSH_DIR=""
SCRIPT_PATH="$0"
if [ -f "$SCRIPT_PATH" ]; then
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" 2>/dev/null && pwd -P)" || true
  # Repo root is the parent of init/ when this file is init/oosh inside a clone
  if [ -n "$SCRIPT_DIR" ] && [ -d "$SCRIPT_DIR/../.git" ]; then
    OOSH_DIR="$(cd "$SCRIPT_DIR/.." && pwd -P)"
  fi
fi
: ${OOSH_DIR:=$HOME/oosh}

# ─── Clone if no .git yet ────────────────────────────────────────────────
# Edge case: $OOSH_DIR exists as a regular FILE, not a directory. This
# happens when `ossh install <host>` SCPs this init/oosh script to
# ~/oosh on the remote and then runs it via `./oosh mode root …` — we
# ARE that file, and $OOSH_DIR resolved to $HOME/oosh = our own path.
# git clone would fail with "destination path already exists". Remove
# the file first — bash has the script slurped into memory, so deleting
# it mid-execution is safe on Unix (inode stays alive for the running
# process; only the directory entry goes).
if [ -e "$OOSH_DIR" ] && [ ! -d "$OOSH_DIR" ]; then
  info.log 2>/dev/null || true
  rm -f "$OOSH_DIR"
fi

# `-e` (not `-d`) — git worktrees store `.git` as a FILE that points back
# at the main repo's `.git/` for that worktree's metadata. State 31 sets
# $HOME/oosh to a symlink pointing at the dev/ worktree, so for re-runs
# of init/oosh (e.g. `ossh install <host> <user>` after the host's
# bootstrap install set up the shared tree), `$OOSH_DIR/.git` resolves
# to that FILE, not a directory. The previous `-d` test failed for that
# case and fell through to `git clone`, which then died with "destination
# path already exists and is not an empty directory". `-e` correctly
# treats both dir-style and file-style `.git` markers as "this is a
# repo, skip the clone".
if [ ! -e "$OOSH_DIR/.git" ]; then
  REPO="${OOSH_REPO:-https://github.com/Cerulean-Circle-GmbH/once.sh.git}"
  echo "Cloning $REPO (branch=$OOSH_BRANCH) into $OOSH_DIR …"
  git clone -b "$OOSH_BRANCH" "$REPO" "$OOSH_DIR" || die "git clone failed"
fi

# ─── Move repo to $HOME/oosh if it's elsewhere ──────────────────────────
# Drag-and-drop from a ZIP would land OOSH_DIR=~/Downloads/once.sh-main/.
# Canonicalize both sides: macOS /var → /private/var symlink makes
# pwd -P resolve $HOME/oosh differently from a bare string concat.
_canon="$HOME/oosh"
[ -d "$HOME" ] && _canon="$(cd "$HOME" && pwd -P)/oosh"
if [ "$OOSH_DIR" != "$_canon" ] && [ "$OOSH_DIR" != "$HOME/oosh" ]; then
  if [ -e "$HOME/oosh" ] && [ ! -L "$HOME/oosh" ]; then
    die "$HOME/oosh already exists and isn't a symlink. Remove or rename it first."
  fi
  rm -f "$HOME/oosh"
  mv "$OOSH_DIR" "$HOME/oosh" || die "could not move $OOSH_DIR to $HOME/oosh"
  OOSH_DIR="$HOME/oosh"
  exec sh "$OOSH_DIR/init/oosh" "$@"
fi
unset _canon

# ─── Env + install log ──────────────────────────────────────────────────
export OOSH_DIR
export PATH="$OOSH_DIR:$PATH"
export INSTALL_LOG="${INSTALL_LOG:-$HOME/config/install.log}"
export BASH_FILE="${BASH_FILE:-$(command -v bash)}"
mkdir -p "$(dirname "$INSTALL_LOG")"
{ echo "# OOSH install log — $(date)"
  echo "# init/oosh (thin bootstrap) handing off to ossh install.continue.local"
} > "$INSTALL_LOG"
[ -n "$LOG_LEVEL_ARG" ] && export LOG_LEVEL="$LOG_LEVEL_ARG"

# ─── Install post-clone prereqs via canonical oosh primitive ────────────
# rsync (used by ossh.config.shared.create at ossh:74) and tree (used by
# user.ssh.status, debug helpers, ossh.status) install here via `ossh
# prereqs.install` LOCAL MODE — runs `oo cmd <pkg>` for each one. This is
# the OOSH-canonical install path: now that we have the framework on disk
# (post-clone) and bash 4+ on PATH, every other dep should install via
# `oo cmd`, NOT via init/oosh's POSIX-sh duplicate. Keeping init/oosh
# minimal per boss feedback (2026-05-08) — see memory
# project_init_oosh_minimal_refactor.
"$OOSH_DIR/this" call ossh prereqs.install || \
  echo "WARNING: ossh prereqs.install (local mode) reported errors — install may still proceed" >&2

# ─── Hand off to the state-machine entrypoint ───────────────────────────
local_name="${REMOTE_SSH_HOST:-$(hostname -s 2>/dev/null || hostname 2>/dev/null || echo localhost)}"
echo "Handing off to ossh install.continue.local (branch=$OOSH_BRANCH, host=$local_name)…"
"$OOSH_DIR/this" call ossh install.continue.local "$local_name" "$CONFIG_REMOTE"
rc=$?

# ─── Install oosh for the invoking user when curl'd as non-root ─────────
# When a non-root user runs the curl one-liner, the sudo re-exec earlier
# landed us as root for the state-machine install above. SUDO_USER is set
# by sudo to the original invoker. Now that root has /home/shared +
# developking in place, set up oosh for that invoker too (symlinks,
# dev-group membership, SSH dotfiles) so the same one-liner yields a
# working shell for BOTH root AND the invoking user.
#
# Skipped when:
#   - SUDO_USER is unset or "root"   → curl/ossh-install ran as root directly
#   - rc != 0                        → state machine failed; don't stack
#                                      a second install on top
# Applies to BOTH curl flow (MODE empty, sudo re-exec from non-root user)
# AND ossh-install-as-non-root (MODE=root, sudo re-exec from test user).
# Either way SUDO_USER identifies the invoker who needs oosh set up for them.
if [ -n "$SUDO_USER" ] && [ "$SUDO_USER" != "root" ] && [ $rc -eq 0 ]; then
  echo ""
  echo "Installing oosh for invoking user: $SUDO_USER"
  if "$OOSH_DIR/user" oosh.install "$SUDO_USER"; then
    # Group membership for the invoking user is refreshed by the above,
    # but the CURRENT shell's group list was captured by sshd/login
    # BEFORE `dev` was added — so bashrc writes to the shared
    # log.live.out hit "Permission denied" until the user re-logs.
    # Unix-wide behaviour; tell the user clearly.
    echo ""
    echo "═════════════════════════════════════════════════════════════════"
    echo "  ✓ oosh installed for root AND $SUDO_USER"
    echo ""
    echo "  NEXT STEP — log out and log back in so '$SUDO_USER' picks up"
    echo "  the new 'dev' group membership. Your current shell still has"
    echo "  the old groups list and will hit 'Permission denied' on shared"
    echo "  files (log.live.out, state machine env, etc.) otherwise."
    echo ""
    echo "  Quick: type  exit  (or Ctrl-D), then ssh back in."
    echo "═════════════════════════════════════════════════════════════════"
  else
    echo "WARNING: user.oosh.install failed for '$SUDO_USER' — see errors above"
  fi
fi

exit $rc
