#!/usr/bin/env bash

# This probe checks whether the registry endpoint answers over HTTP.  The
# endpoint may return an HTTP error (for example, 404) while the forward is
# reachable, so curl's transport exit status is the health signal.

registry_url='http://100.101.104.41:4873/-/ping'

# Keep curl's machine-readable timing and error fields together.  In
# particular, do not use --fail: a response from the registry is reachability
# even when this installation does not serve the requested path.
curl_result=$(curl \
    --silent \
    --max-time 5 \
    --output /dev/null \
    --write-out '%{http_code}\t%{time_total}\t%{exitcode}\t%{errormsg}' \
    "$registry_url")
curl_status=$?

http_code='000'
elapsed='0'
curl_exit="$curl_status"
curl_error=''
IFS=$'\t' read -r http_code elapsed curl_exit curl_error <<< "$curl_result"

if (( curl_status != 0 )); then
    if [[ -n "$curl_error" ]]; then
        error_text="curl: ($curl_exit) $curl_error"
    else
        error_text="curl exited with status $curl_status"
    fi
    error_text=${error_text//$'\n'/ }
    error_text=${error_text//$'\r'/ }
    printf 'REGISTRY DOWN: platform registry at 100.101.104.41:4873 unreachable (%s). This is an infrastructure outage on debian3 (socat forward / k3s registry), NOT a lockfile problem — do not chase ERR_PNPM_TARBALL_URL_MISMATCH or lockfile policy errors until the registry answers.\n' "$error_text"
    exit 1
fi

# Convert curl's decimal seconds to whole milliseconds using Bash built-ins.
whole_seconds='0'
fractional_seconds='0'
IFS=. read -r whole_seconds fractional_seconds <<< "$elapsed"
[[ -n "$whole_seconds" ]] || whole_seconds='0'
[[ -n "$fractional_seconds" ]] || fractional_seconds='0'
fractional_seconds="${fractional_seconds}000"
fractional_seconds=${fractional_seconds:0:3}
while ((${#fractional_seconds} < 3)); do
    fractional_seconds="${fractional_seconds}0"
done
whole_milliseconds="${whole_seconds}000"
elapsed_ms=$((10#$whole_milliseconds + 10#$fractional_seconds))
printf 'registry OK (%sms)\n' "$elapsed_ms"
exit 0
