#!/usr/bin/env bash
#
# mokocli-deploy.sh - canonical mokocli loader (Linux / macOS).
# Windows parity: mokocli-deploy.ps1 in this directory (identical resolution order).
#
# @package   MokoEnterprises repo standards (Template-Generic -> fleet via Sync Profile #10)
# @copyright Copyright (C) 2026 Moko Enterprises. All rights reserved.
# @license   GNU General Public License version 3 or later; see LICENSE
#
# SINGLE source of truth for "how a build host obtains mokocli". It replaces the
# per-workflow inline "Setup MokoCLI tools" block so every repo's CI AND a
# developer's local machine resolve mokocli IDENTICALLY (Windows + Linux).
#
# Resolution order (security-reviewed - see SECURITY below):
#   1. /opt/mokocli (root-owned PRIMARY): the runner image bakes a fresh /opt on every
#      mokocli stable ladder, so when a trusted, root-owned /opt already carries the
#      pinned MOKOCLI_VERSION (or newer) it is used DIRECTLY - no registry round-trip,
#      no composer/apt. A STALE /opt (older than the pin) falls through to the registry
#      below, so a lagging baked image can never shadow the pinned release (#1671
#      intent, now pin-relative and round-trip-free).
#   2. REGISTRY (FALLBACK): install the PINNED mokocli (env MOKOCLI_VERSION, #546)
#      fresh from the MokoGIT Composer registry. /api/packages/** is anon-allowlisted
#      (no token); it serves a dist zip (no git clone). Within this path the #1671
#      /opt-strictly-newer preference is retained.
#   3. /opt/mokocli (root-owned FAILSAFE): registry install failed - use any trusted
#      root-owned /opt even if older than the pin (better stale than nothing).
#   4. ~/mokocli (operator-provisioned LAST-RESORT): used ONLY when the registry AND
#      /opt are unavailable. READ-ONLY - this script NEVER writes ~/mokocli.
#   5. else: hard error (exit 1).
#
# SECURITY (CI/CD supply-chain / persistent tool poisoning): a WRITABLE $HOME cache
# that privileged release jobs PREFER and auto-populate is a poisoning vector on
# shared/persistent runners - a job in any repo could trojan the `moko` the next
# release job executes. Per that review, ~/mokocli here is a READ-ONLY, LAST-RESORT
# fallback: never preferred over the registry/opt, and never written by this script.
# For outage resilience, pre-provision ~/mokocli (or /opt) out-of-band, root-owned
# and read-only.
#
# Usage:
#   bash mokocli-deploy.sh            # resolve + (in CI) export MOKO_CLI/PATH; prints MOKO_CLI=<dir>
#   bash mokocli-deploy.sh --print    # resolve QUIETLY, print ONLY the cli dir (for Makefile $(shell))
#   bash mokocli-deploy.sh --soft     # best-effort: on total failure emit empty MOKO_CLI + exit 0
#                                     # (for optional consumers like apidocs / the CI issue-reporter
#                                     #  that must DEGRADE, never go red, when mokocli is unavailable)
# Flags combine (e.g. --print --soft).
#
# CI vs local: under Actions (GITHUB_ENV set) it appends MOKO_CLI to GITHUB_ENV and
# the bin/cli dirs to GITHUB_PATH for later steps. Locally it prints MOKO_CLI=<dir>
# as the last stdout line (bare dir with --print).
set -u

MOKOCLI_VERSION="${MOKOCLI_VERSION:-10.34.00}"
MOKOGIT_URL="${MOKOGIT_URL:-https://git.mokoenterprises.us}"
MOKO_ORG="${MOKOGIT_ORG:-MokoEnterprises}"
HOME_MOKO="${HOME:-$HOME}/mokocli"

PRINT_ONLY=0
SOFT=0
for arg in "$@"; do
  case "$arg" in
    --print) PRINT_ONLY=1 ;;
    --soft)  SOFT=1 ;;
    *) echo "mokocli-deploy.sh: unknown argument '$arg'" >&2; exit 2 ;;
  esac
done

# All human/diagnostic output goes to stderr so --print stdout stays clean for capture.
log() { echo "$@" >&2; }

# Add a mokocli root's bin/cli to PATH (#650), emitting GITHUB_PATH in CI.
#   $1 = mokocli root (contains bin/ and/or cli/)
#   $2 = mode:
#     "rw" - also HARDEN the launcher: make it executable + strip CR bytes so a
#            CRLF-tainted dist can't yield `/usr/bin/env: 'php\r'` (#1263). Used ONLY
#            for the fresh registry /tmp copy, which the job OWNS - so no sudo is ever
#            needed (this script performs NO privileged writes). Staging goes through
#            mktemp, never a fixed /tmp path.
#     "ro" - READ-ONLY: PATH only, NO writes. Used for the root-owned /opt failsafe and
#            the ~/mokocli last-resort, so a tree we don't own is never modified.
add_to_path() {
  local root="$1" mode="$2" d tmp
  for d in bin cli; do
    [ -f "${root}/$d/moko" ] || continue
    if [ "$mode" = "rw" ]; then
      tmp="$(mktemp 2>/dev/null)" || tmp=""
      if [ -n "$tmp" ] && tr -d '\r' < "${root}/$d/moko" > "$tmp" 2>/dev/null; then
        cp "$tmp" "${root}/$d/moko" 2>/dev/null || true
        rm -f "$tmp"
      fi
      chmod +x "${root}/$d/moko" 2>/dev/null || true
    fi
    [ -n "${GITHUB_PATH:-}" ] && echo "${root}/$d" >> "$GITHUB_PATH"
  done
}

# Resolve done: export MOKO_CLI (CI) + print the result, then exit 0. $1 = cli dir.
finish() {
  local cli="$1"
  [ -n "${GITHUB_ENV:-}" ] && echo "MOKO_CLI=${cli}" >> "$GITHUB_ENV"
  if [ "$PRINT_ONLY" = "1" ]; then
    echo "${cli}"
  else
    echo "MOKO_CLI=${cli}"
  fi
  exit 0
}

mk_ver()    { sed -n 's/^[[:space:]]*PROJECT_VERSION[[:space:]]*:*=[[:space:]]*//p' "$1" 2>/dev/null | head -n1 | tr -d '[:space:]'; }
ver_newer() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ]; }

# True if $1 is a directory tree the CURRENT user cannot tamper with: every entry
# owned by root AND nothing group/world-writable. Used to gate root-copy sources and
# the CI ~/mokocli trust decision. Empty `find` output => clean.
tree_is_root_readonly() {
  [ -d "$1" ] && [ ! -L "$1" ] \
    && [ -z "$(find "$1" \( ! -user root -o -perm /022 \) -print -quit 2>/dev/null)" ]
}

# True if $1 is a TAMPER-PROOF tree: its parent is not writable by us (so the dir
# can't be swapped) AND the whole tree is root-owned + not group/world-writable (so no
# entry can be modified). Gates every path this script TRUSTS but does not own
# (/opt, and the CI ~/mokocli last-resort).
locked_readonly_tree() {
  [ -d "$1" ] || return 1
  [ -w "$(dirname "$1")" ] && return 1
  tree_is_root_readonly "$1"
}

# Whether the CI ~/mokocli last-resort may be trusted. Fails CLOSED in CI: trust only a
# genuinely pre-provisioned, tamper-proof tree. Locally (no GITHUB_ENV) the dir is the
# developer's own and is trusted.
home_cache_trusted() {
  [ -z "${GITHUB_ENV:-}" ] && return 0
  locked_readonly_tree "$HOME_MOKO"
}

# True if $1 is a tree OWNED BY THE CURRENT USER and not group/world-writable - i.e. we
# have exclusive control. Used to confirm the just-created /tmp/mokocli install was not
# pre-planted or tampered before we trust + export it.
tree_is_ours_locked() {
  local me; me="$(id -u 2>/dev/null)"
  [ -d "$1" ] && [ ! -L "$1" ] \
    && [ -z "$(find "$1" \( ! -uid "$me" -o -perm /022 \) -print -quit 2>/dev/null)" ]
}

# ---------------------------------------------------------------------------
# 1. /opt/mokocli (root-owned PRIMARY) - baked into the runner image on every mokocli
#    stable ladder. Use it DIRECTLY (read-only, NO registry round-trip, NO composer)
#    whenever it is a locked, root-owned tree AND already carries the pinned
#    MOKOCLI_VERSION or newer. A stale /opt (older than the pin, or unversioned) falls
#    through to the registry install below - so a lagging baked image can't shadow the
#    pinned release. This is the common case, and it runs BEFORE the composer-ensure
#    step so a trusted-/opt job never triggers an apt-get.
if [ -f /opt/mokocli/cli/version_bump.php ] && locked_readonly_tree /opt/mokocli; then
  OPT_VER="$(mk_ver /opt/mokocli/Makefile)"
  if [ -n "$OPT_VER" ] && { [ "$OPT_VER" = "$MOKOCLI_VERSION" ] || ver_newer "$OPT_VER" "$MOKOCLI_VERSION"; }; then
    log "Using /opt/mokocli (${OPT_VER}) PRIMARY - baked, root-owned read-only, >= pinned ${MOKOCLI_VERSION}; no registry round-trip."
    add_to_path /opt/mokocli ro
    finish /opt/mokocli/cli
  else
    log "::notice::/opt/mokocli present (${OPT_VER:-unversioned}) but < pinned ${MOKOCLI_VERSION} - falling through to the registry install."
  fi
fi

# Ensure composer is present (CI runners may lack it; best-effort, needs sudo).
# Only reached when /opt was not a trusted, current tree (i.e. we must hit the registry).
if ! command -v composer > /dev/null 2>&1; then
  sudo apt-get update -qq && sudo apt-get install -y -qq php-cli php-mbstring php-xml php-zip php-curl composer > /dev/null 2>&1 || true
fi

# ---------------------------------------------------------------------------
# 2. REGISTRY (FALLBACK) - pinned install (#546), with #1671 /opt-newer preference.
#    Reached only when /opt is absent, untrusted, or stale (older than the pin).
# ---------------------------------------------------------------------------
# /tmp/mokocli is a FIXED path (not mktemp) because ci-joomla's downstream steps probe
# it by name. Guard the predictable path (TOCTOU): `[ ! -e /tmp/mokocli ]` fails CLOSED
# if a prior/foreign /tmp/mokocli couldn't be removed, and `tree_is_ours_locked` after
# install rejects a pre-planted/tampered tree before we trust + export it.
rm -rf /tmp/mokocli 2>/dev/null || true
# Use --repository-url (plain URL), NOT --repository='{json}': the JSON form has its
# quotes stripped passing through composer.bat / cmd.exe on Windows, breaking the
# install. --repository-url is equivalent for a composer repo and works on every OS.
if [ ! -e /tmp/mokocli ] \
   && command -v composer > /dev/null 2>&1 \
   && composer create-project --no-install --no-interaction --no-progress --quiet \
        --repository-url="${MOKOGIT_URL}/api/packages/${MOKO_ORG}/composer" "mokoenterprises/mokocli:${MOKOCLI_VERSION}" /tmp/mokocli >/dev/null 2>&1 \
   && [ -f /tmp/mokocli/cli/version_bump.php ] \
   && tree_is_ours_locked /tmp/mokocli; then
  log "Installed mokocli ${MOKOCLI_VERSION} (pinned, #546) fresh from the Composer registry (primary)"

  # #1671 publish-lag race: prefer /opt only when it is strictly NEWER than the
  # registry copy (registry can serve the PREVIOUS package for ~tens of seconds).
  # SECURITY: /opt is only ever preferred (or used below as a fallback) when it is a
  # locked, root-owned read-only tree the runner cannot tamper with, so it can never
  # override the pin with attacker-controlled code. This script performs NO privileged
  # writes: /opt is provisioned out-of-band (root-owned, read-only); there is no
  # opportunistic sudo refresh of /opt from CI.
  REG_VER="$(mk_ver /tmp/mokocli/Makefile)"
  MOKO_ROOT=/tmp/mokocli
  if [ -f /opt/mokocli/cli/version_bump.php ] && locked_readonly_tree /opt/mokocli; then
    OPT_VER="$(mk_ver /opt/mokocli/Makefile)"
    if [ -n "$OPT_VER" ] && [ -n "$REG_VER" ] && ver_newer "$OPT_VER" "$REG_VER"; then
      log "::notice::/opt/mokocli (${OPT_VER}) is newer than the registry copy (${REG_VER}) - using /opt (#1671 publish-lag race)."
      MOKO_ROOT=/opt/mokocli
    else
      log "Using registry copy (${REG_VER:-unknown}); /opt/mokocli=${OPT_VER:-none}"
    fi
  else
    log "Using registry copy (${REG_VER:-unknown}); /opt/mokocli not a trusted root-owned tree."
  fi

  # /opt is root-owned read-only -> ro (PATH only); the /tmp copy is ours -> rw (harden).
  if [ "$MOKO_ROOT" = /opt/mokocli ]; then add_to_path /opt/mokocli ro; else add_to_path /tmp/mokocli rw; fi
  finish "${MOKO_ROOT}/cli"
fi

# ---------------------------------------------------------------------------
# 3. /opt/mokocli (root-owned FAILSAFE) - registry install failed (or /opt was older
#    than the pin in step 1). Trusted ONLY when it is a locked, root-owned read-only
#    tree; used read-only (no writes). Better a stale baked mokocli than none.
# ---------------------------------------------------------------------------
if [ -f /opt/mokocli/cli/version_bump.php ] && locked_readonly_tree /opt/mokocli; then
  log "::warning::Registry install failed - using /opt/mokocli FAILSAFE (root-owned, may be stale)"
  add_to_path /opt/mokocli ro
  finish /opt/mokocli/cli
fi

# ---------------------------------------------------------------------------
# 4. ~/mokocli (operator-provisioned LAST-RESORT) - registry AND /opt unavailable.
#    READ-ONLY: added to PATH as-is, NEVER written here (add_to_path ... ro).
#    Supply-chain gate: in CI a $HOME copy that the RUNNER USER can write is a
#    poisoning vector, so trust it ONLY when it is NOT writable by us (pre-provisioned
#    root-owned + read-only). Locally (no GITHUB_ENV) it is the developer's own dir.
# ---------------------------------------------------------------------------
if [ -f "${HOME_MOKO}/cli/version_bump.php" ] || [ -f "${HOME_MOKO}/cli/moko" ] || [ -f "${HOME_MOKO}/bin/moko" ]; then
  if home_cache_trusted; then
    log "::warning::Registry AND /opt/mokocli unavailable - using READ-ONLY last-resort ${HOME_MOKO}."
    add_to_path "$HOME_MOKO" ro
    finish "${HOME_MOKO}/cli"
  else
    log "::warning::Ignoring ${HOME_MOKO} in CI: not a tamper-proof root-owned read-only tree (tool-poisoning risk). Pre-provision it root-owned, non-writable, under a non-writable parent to use as a CI last resort."
  fi
fi

# ---------------------------------------------------------------------------
# 5. Nothing resolved.
# ---------------------------------------------------------------------------
if [ "$SOFT" = 1 ]; then
  log "::warning::mokocli unavailable (--soft): registry install failed, no /opt/mokocli failsafe, no ${HOME_MOKO} last-resort copy. Continuing with empty MOKO_CLI - dependent steps will degrade/skip."
  [ -n "${GITHUB_ENV:-}" ] && echo "MOKO_CLI=" >> "$GITHUB_ENV"
  [ "$PRINT_ONLY" = 1 ] && echo ""
  exit 0
fi
log "::error::mokocli unavailable: registry install failed, no /opt/mokocli failsafe, and no ${HOME_MOKO} last-resort copy."
exit 1
