#!/bin/sh
# Combined read-only POSIX prepare probe: platform facts + directory roots in
# ONE SSH session.
#
# Only cheap, home-independent segments live here. CBC discovery stays on its
# own step: probing candidates on a target without CBC routinely takes
# seconds, and folding it in blew the probe step budget (504 timeouts).
#
# Output: the segments keep their original protocol framing, separated by
# CODEBUDDY_COMBINED_SEG_<NAME>_END markers; a failing segment only marks
# itself FAILED and never blocks the following segments.
set -eu

work_dir=$(mktemp -d "${TMPDIR:-/tmp}/cbc-combined.XXXXXX")
trap 'rm -rf "$work_dir"' EXIT
platform_out="$work_dir/platform-output"

(
# Read-only POSIX platform probe.
#
# One SSH round trip already costs more than this script should. Facts come
# from a single `uname` and, on macOS, a single `sysctl`. JSON is built in
# the shell so a normal home path does not fork sed/tr per field. The
# versioned envelope stays: stdout may still carry a login banner.


MARKER='CODEBUDDY_PLATFORM_PROBE_V1'
TERMINATOR='CODEBUDDY_PLATFORM_PROBE_END_V1'

# Quote a string or emit null. Control bytes (not UTF-8) become null so the
# decoder never has to accept them. Backslash and quote are escaped in-process.
json_string_or_null() {
    if [ -z "${1-}" ]; then
        printf 'null'
        return
    fi
    rest=$1
    out=
    while [ -n "$rest" ]; do
        char=${rest%"${rest#?}"}
        rest=${rest#?}
        case $char in
            [[:cntrl:]])
                printf 'null'
                return
                ;;
            \\) out="${out}\\\\" ;;
            \") out="${out}\\\"" ;;
            *) out="${out}${char}" ;;
        esac
    done
    printf '"%s"' "$out"
}

command_exists() {
    command -v "$1" >/dev/null 2>&1
}

uname_line=$(uname -sm 2>/dev/null || true)
uname_s=${uname_line%% *}
uname_m=${uname_line#* }
if [ "$uname_m" = "$uname_line" ]; then
    uname_m=
fi

os='unknown'
case "$uname_s" in
    Darwin) os='macos' ;;
    Linux) os='linux' ;;
esac

kernel_arch='other'
case "$uname_m" in
    x86_64|amd64) kernel_arch='x64' ;;
    arm64|aarch64) kernel_arch='arm64' ;;
    i386|i486|i586|i686) kernel_arch='x86' ;;
    armv7l|armv6l) kernel_arch='arm32' ;;
    '') kernel_arch='unknown' ;;
esac

native_arch=$kernel_arch
process_arch=$kernel_arch
rosetta='notApplicable'
if [ "$os" = 'macos' ] && command_exists sysctl; then
    # Two keys, one process. Empty proc_translated stays "notApplicable".
    sysctl_out=$(sysctl -n hw.machine sysctl.proc_translated 2>/dev/null || true)
    saved_ifs=$IFS
    IFS='
'
    # shellcheck disable=SC2086
    set -- $sysctl_out
    IFS=$saved_ifs
    sysctl_machine=${1-}
    sysctl_opt=${2-}
    case "$sysctl_machine" in
        arm64) native_arch='arm64' ;;
        x86_64) native_arch='x64' ;;
    esac
    case "$process_arch" in
        arm64|x64) ;;
        *) process_arch=$native_arch ;;
    esac
    if [ "$sysctl_opt" = '1' ]; then
        rosetta='translated'
        native_arch='arm64'
        process_arch='x64'
    elif [ -n "$sysctl_opt" ]; then
        rosetta='native'
    fi
elif [ "$os" = 'macos' ]; then
    rosetta='unknown'
fi

libc='unknown'
libc_version='null'
if [ "$os" = 'linux' ] && command_exists getconf; then
    gnu_libc=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
    case "$gnu_libc" in
        glibc\ *)
            libc='glibc'
            libc_version=$(json_string_or_null "${gnu_libc#glibc }")
            ;;
        musl)
            libc='musl'
            ;;
        '')
            if [ -r /etc/alpine-release ]; then
                libc='musl'
            fi
            ;;
    esac
elif [ "$os" = 'linux' ] && [ -r /etc/alpine-release ]; then
    libc='musl'
fi

wsl='none'
if [ "$os" = 'linux' ]; then
    kernel_release=$(uname -r 2>/dev/null || true)
    case "$kernel_release" in
        *[Mm]icrosoft*WSL2*|*WSL2*) wsl='wsl2' ;;
        *[Mm]icrosoft*WSL1*|*WSL1*) wsl='wsl1' ;;
        *[Mm]icrosoft*) wsl='unknown' ;;
    esac
    if [ "$wsl" = 'none' ] && [ -r /proc/version ]; then
        IFS= read -r proc_version < /proc/version || proc_version=
        case "$proc_version" in
            *[Mm]icrosoft*) wsl='unknown' ;;
        esac
    fi
fi

home_value=${HOME-}
user_id=
if command_exists id; then
    user_id=$(id -u 2>/dev/null || true)
fi

shell_kind='unknown'
case "${SHELL##*/}" in
    sh|bash|zsh|ksh) shell_kind=${SHELL##*/} ;;
esac

if command_exists curl; then tool_curl=true; else tool_curl=false; fi
if command_exists tar; then tool_tar=true; else tool_tar=false; fi
if command_exists unzip; then tool_unzip=true; else tool_unzip=false; fi
if command_exists sha256sum || command_exists shasum; then tool_sha256=true; else tool_sha256=false; fi

os_version=$(uname -r 2>/dev/null || true)
payload=$(printf '%s' "{\"schemaVersion\":1,\"probeKind\":\"posix\",\"os\":\"$os\",\"osVersion\":$(json_string_or_null "$os_version"),\"kernelArch\":\"$kernel_arch\",\"nativeArch\":\"$native_arch\",\"processArch\":\"$process_arch\",\"libc\":\"$libc\",\"libcVersion\":$libc_version,\"wsl\":\"$wsl\",\"rosetta\":\"$rosetta\",\"home\":$(json_string_or_null "$home_value"),\"userId\":$(json_string_or_null "$user_id"),\"shellKind\":\"$shell_kind\",\"tools\":{\"curl\":$tool_curl,\"tar\":$tool_tar,\"unzip\":$tool_unzip,\"sha256\":$tool_sha256},\"diskFreeBytes\":null,\"desktop\":{\"present\":null,\"kind\":null}}")

if command_exists base64; then
    encoded=$(printf '%s' "$payload" | base64 | tr -d '\n')
else
    encoded=
fi

if [ -z "$encoded" ]; then
    exit 1
fi

printf '%s\n' "$MARKER"
printf '%s\n' "$encoded"
printf '%s\n' "$TERMINATOR"

) >"$platform_out" || printf 'CODEBUDDY_COMBINED_SEG_PLATFORM_FAILED\n'
cat "$platform_out"
printf '\nCODEBUDDY_COMBINED_SEG_PLATFORM_END\n'

# The local controller already knows the release. Look only at that directory.
# `current` may point at an older local build; do not follow it.
(
    set +e
    want=${CBC_WANT_VERSION:-}
    case "$want" in
        [0-9]*.[0-9]*.[0-9]*) ;;
        *) want= ;;
    esac
    home=${HOME:-}
    remote=$home/.local/share/codebuddy/remote
    target=
    if [ -n "$want" ] && [ -n "$home" ]; then
        for name in codebuddy cbc; do
            candidate=$remote/releases/$want/bin/$name
            if [ -f "$candidate" ] || [ -x "$candidate" ]; then
                target=$candidate
                break
            fi
        done
    fi
    if [ -n "$target" ]; then
        path_hex=$(printf '%s' "$target" | od -An -tx1 | tr -d ' \n')
        version_hex=$(printf '%s' "$want" | od -An -tx1 | tr -d ' \n')
        printf '%s\n' "{\"schemaVersion\":1,\"platform\":\"posix\",\"candidates\":[{\"executablePath\":\"hex:${path_hex}\",\"versionOutput\":\"hex:${version_hex}\",\"product\":\"codebuddy\",\"protocolMin\":null,\"protocolMax\":null,\"protocolRaw\":null,\"executable\":true,\"probeSucceeded\":true,\"nodeDir\":null}]}"
    else
        printf '%s\n' '{"schemaVersion":1,"platform":"posix","candidates":[]}'
    fi
) || printf '%s\n' '{"schemaVersion":1,"platform":"posix","candidates":[]}'
printf '\nCODEBUDDY_COMBINED_SEG_DISCOVERY_END\n'

(
# Fixed, read-only POSIX directory browser.
#
# stdin is one bounded JSON request. Paths are emitted as hex:<lowercase>
# so names keep spaces and non-ASCII bytes without a JSON runtime.
#
# Listing used to fork `od` once per name. A home directory of a few hundred
# folders took seconds. This script lists with one `find` and hex-encodes the
# whole batch in one `od`.


MAX_REQUEST_BYTES=8192
MAX_PATH_BYTES=4096
MAX_CHILDREN=256

# The invoker writes one JSON line and a newline. read returns on that
# newline, so a short request does not wait to fill a block.
IFS= read -r request || true
if [ "${#request}" -gt "$MAX_REQUEST_BYTES" ] || [ -z "$request" ]; then
    exit 2
fi

json_string_field() {
    field=$1
    printf '%s' "$request" | sed -n "s/.*\"$field\"[[:space:]]*:[[:space:]]*\"\\([^\"\\\\]*\\)\".*/\\1/p" | head -n 1
}

decode_path_base64() {
    encoded=$1
    case "$encoded" in
        *[!A-Za-z0-9+/=]*|'') return 1 ;;
    esac
    printf '%s' "$encoded" | base64 -d 2>/dev/null
}

# One process for one string. Roots mode only calls this a handful of times.
hex_string() {
    encoded=$(printf '%s' "$1" | od -An -tx1 | tr -d ' \n')
    printf '"hex:%s"' "$encoded"
}

json_null() {
    printf 'null'
}

emit_roots() {
    printf '{"schemaVersion":1,"platform":"posix","home":'
    if [ -n "${HOME-}" ]; then hex_string "$HOME"; else json_null; fi
    printf ',"roots":[{"path":'
    hex_string '/'
    printf ',"label":'
    hex_string '/'
    printf '}],"current":null,"parent":null,"children":[],"truncated":false,"encoding":"utf8"}\n'
}

# Hex-encode every NUL-terminated path in $1 with a single od.
# stdout line 1 is the JSON array body; line 2 is 1 when the listing was cut.
emit_children_json() {
    list_file=$1
    LC_ALL=C od -An -tx1 -v "$list_file" | awk -v max_children="$MAX_CHILDREN" -v max_bytes="$MAX_PATH_BYTES" -v max_output=48000 '
        function basename_hex(value,    pos) {
            for (pos = length(value) - 1; pos > 0; pos -= 2) {
                if (substr(value, pos, 2) == "2f") {
                    return substr(value, pos + 2)
                }
            }
            return value
        }
        function emit_path(value,    pair_count, name, piece) {
            if (truncated || value == "") {
                return
            }
            pair_count = length(value) / 2
            if (pair_count > max_bytes) {
                return
            }
            if (count >= max_children) {
                truncated = 1
                return
            }
            name = basename_hex(value)
            piece = sprintf("{\"name\":\"hex:%s\",\"path\":\"hex:%s\",\"kind\":\"directory\"}", name, value)
            if (count > 0) {
                piece = "," piece
            }
            if (output_bytes + length(piece) > max_output) {
                truncated = 1
                return
            }
            printf "%s", piece
            output_bytes += length(piece)
            count++
        }
        BEGIN { count = 0; truncated = 0; buf = ""; output_bytes = 0 }
        {
            if (truncated) {
                next
            }
            for (i = 1; i <= NF; i++) {
                if ($i == "00") {
                    emit_path(buf)
                    buf = ""
                } else {
                    buf = buf $i
                }
            }
        }
        END {
            emit_path(buf)
            printf "\n%d\n", truncated ? 1 : 0
        }
    '
}

emit_children() {
    target=$1
    case "$target" in
        /) target='/' ;;
        //) target='/' ;;
        */) target=${target%/} ;;
    esac
    if [ -z "$target" ] || [ "${#target}" -gt "$MAX_PATH_BYTES" ]; then
        exit 3
    fi
    if [ ! -d "$target" ]; then
        exit 4
    fi

    list_file=$(mktemp "${TMPDIR:-/tmp}/cbc-dirs.XXXXXX") || exit 4
    # -print0 keeps spaces. find -L follows a symlink-to-directory the same
    # way `[ -d ]` did, and -maxdepth stops it from walking the tree.
    find -L "$target" -mindepth 1 -maxdepth 1 -type d -print0 > "$list_file" 2>/dev/null || true

    body_file=$(mktemp "${TMPDIR:-/tmp}/cbc-dirs-json.XXXXXX") || { rm -f "$list_file"; exit 4; }
    emit_children_json "$list_file" > "$body_file"
    children=$(sed -n '1p' "$body_file")
    truncated=$(sed -n '2p' "$body_file")
    rm -f "$list_file" "$body_file"
    if [ "$truncated" != 1 ]; then
        truncated=0
    fi

    parent=
    case "$target" in
        /) parent= ;;
        */*) parent=${target%/*}; [ -n "$parent" ] || parent='/' ;;
    esac

    printf '{"schemaVersion":1,"platform":"posix","home":'
    if [ -n "${HOME-}" ]; then hex_string "$HOME"; else json_null; fi
    printf ',"roots":[{"path":'
    hex_string '/'
    printf ',"label":'
    hex_string '/'
    printf '}],"current":'
    hex_string "$target"
    printf ',"parent":'
    if [ -n "$parent" ]; then hex_string "$parent"; else json_null; fi
    if [ "$truncated" = 1 ]; then
        trunc_json=true
    else
        trunc_json=false
    fi
    printf ',"children":[%s],"truncated":%s,"encoding":"utf8"}\n' "$children" "$trunc_json"
}

mode=$(json_string_field mode)
case "$mode" in
    roots) emit_roots ;;
    children)
        path_base64=$(json_string_field pathBase64)
        decoded_path=$(decode_path_base64 "$path_base64") || exit 3
        emit_children "$decoded_path"
        ;;
    *) exit 5 ;;
esac

) <<'CODEBUDDY_COMBINED_ROOTS_REQUEST' || printf 'CODEBUDDY_COMBINED_SEG_DIRPROBE_FAILED\n'
{"mode":"roots"}
CODEBUDDY_COMBINED_ROOTS_REQUEST
printf '\nCODEBUDDY_COMBINED_SEG_DIRPROBE_END\n'
