# pp.sh - pipe console output to Paste-Post (T11; canonical home moved by T12).
#
# Canonical file: backend/app/web/static/pp.sh - baked into the backend image
# and served raw by the api at GET /pp.sh (text/x-shellscript). The bootstrap
# installer at GET /install.sh (`curl -fsSL <site>/install.sh | bash`, T12)
# embeds these exact contents into the managed marker block it writes to
# ~/.bashrc / ~/.zshrc; the on-site instructions live at GET /how-to.
# scripts/shell/pp.sh is a relative symlink pointing here, kept so the
# existing host usage below keeps working unchanged.
#
# Defines ONE POSIX sh function, `pp`. Works in POSIX sh, bash and zsh; the
# only dependency is curl. Two ways to use it:
#
#   1) Source it (the usual install; nothing runs on `.`):
#        . /path/to/pp.sh          # or copy the pp function into ~/.bashrc/
#                                  # ~/.zshrc
#      then pipe into pb:
#        some-command | pp
#
#   2) Execute it as a pipe filter (no install):
#        echo hello | bash /path/to/pp.sh
#        echo hello | sh /path/to/pp.sh "expiry=1h&burn=1"
#
# Usage:
#   some-command | pp                          # upload stdin, print the URL
#   dmesg | tail -5 | pp                       # same
#   cat err.log | pp "title=build%20log&lang=python"
#   dmesg | pp "expiry=1h&burn=1"              # query string as 1st argument
#   PP_URL=https://pp.example.org sh -c 'dmesg | pp'   # another instance
#
# The optional first argument is the RAW query string appended after the "?"
# of /api/v1/pastes/raw (a leading "?" on it is tolerated). Supported keys:
#   lang=<name>        syntax highlighting language (unknown -> plaintext)
#   expiry=<name>      10min 1h 1day 1week 1month 6months 1year never
#   visibility=<name>  public unlisted private - DEFAULT IS UNLISTED, so
#                      console dumps never land in public listings
#   burn=1|true        delete the paste after the first view
#   title=<text>       explicit title (URL-encode it); else server auto-title
# Values must be URL-encoded ("my%20log", not "my log").
#
# Prints exactly one line on success: the absolute URL of the paste view.
# The one-time delete token is not shown in this mode - use JSON mode when
# you need it (README, "Console pipe upload"):
#   echo hi | curl -sS --data-binary @- -H 'Accept: application/json' "$PP_URL/api/v1/pastes/raw"
#
# PP_URL: base URL of this Paste-Post instance, default http://localhost:8888 (the
# compose stack's PP_HTTP_PORT; no trailing slash). Read fresh on every call.
pp() {
    # Optional first argument: raw query string (a leading "?" is tolerated).
    _pp_query=""
    if [ "$#" -gt 0 ] && [ -n "$1" ]; then
        case "$1" in
            "?"*) _pp_query="$1" ;;
            *) _pp_query="?$1" ;;
        esac
    fi
    # Base URL: env override or the default; a trailing slash is trimmed so
    # the endpoint path always joins cleanly.
    _pp_base="${PP_URL:-http://localhost:8888}"
    _pp_base="${_pp_base%/}"
    # -sS: silent but still report network errors on stderr.
    # --data-binary @- streams stdin byte-exact (no CR-LF mangling) as the
    # raw request body.
    _pp_url="$(curl -sS --data-binary @- "${_pp_base}/api/v1/pastes/raw${_pp_query}")" || {
        _pp_rc=$?
        unset _pp_query _pp_base _pp_url
        return "$_pp_rc"
    }
    # One line, no trailing junk: command substitution already stripped any
    # trailing newline from the response; printf adds exactly one back.
    printf '%s\n' "$_pp_url"
    unset _pp_query _pp_base _pp_url
}

# Run only when EXECUTED as a script ("echo hi | sh pp.sh"), never when
# sourced (sourcing must only define pp).
# - zsh sets $0 to the sourced file's name, so $0 alone cannot distinguish
#   there; while sourcing, ZSH_EVAL_CONTEXT gains a "file" entry.
# - POSIX sh / bash: while sourced, $0 stays the invoking shell (or the
#   sourcing script) and is never this file.
_pp_run=""
if [ -n "${ZSH_EVAL_CONTEXT:-}" ]; then
    case "${ZSH_EVAL_CONTEXT}" in
        *file*) : ;;        # zsh is sourcing this file: define pp only
        *) _pp_run=1 ;;     # zsh is executing it as a script
    esac
else
    case "${0##*/}" in
        pp.sh) _pp_run=1 ;;
    esac
fi
if [ -n "$_pp_run" ]; then
    pp "$@"
fi
unset _pp_run
