#!/bin/sh
# install.sh - T12 bootstrap installer for the `pp` console function.
#
# Served by the api at GET /install.sh with two placeholders substituted per
# request (app.web.routes_ui.compose_installer; the placeholder tokens are
# intentionally spelled out only inside the block below, never in comments):
#   - the PP_URL token -> absolute base URL of THIS deployment, built from the
#     request's Host header (scheme honors X-Forwarded-Proto; a missing/empty
#     Host falls back to the compose default http://localhost:8888)
#   - the PP_FUNCTION token -> the current contents of pp.sh (canonical file:
#     backend/app/web/static/pp.sh, also served at GET /pp.sh)
#
# Typical use:  curl -fsSL http://<host>:8888/install.sh | bash
#
# Design rules (docs/TICKETS.md T12):
# - POSIX sh with `set -eu`; ALL output goes to stderr so stdout stays clean.
# - PIPE-SAFE: under `curl | bash` stdin IS the pipe - the installer never
#   reads it. Prompts read from /dev/tty, guarded by
#   [ -e /dev/tty ] && [ -t 2 ] (stderr attached to a terminal proves we have
#   a controlling terminal). Without a tty (CI, nohup) everything
#   auto-proceeds with the $SHELL-derived default rc file.
# - Idempotent: the managed marker block below is REPLACED in place on
#   re-runs - never duplicated - so the last install wins (including a new
#   PP_URL when re-run from another host). The rc file is backed up to
#   <rc>.pp-bak-<epoch> once, before the first modification only.
# - Uninstall: delete the marked block from the rc file(s).

set -eu

msg()  { printf '%s\n' "$*" >&2; }
fail() { printf 'pp installer: ERROR: %s\n' "$*" >&2; exit 1; }

# Absolute base URL of this Paste-Post deployment, baked in per request by the server.
pp_url='https://222-167-216-60.nip.io'

# The managed rc block: one PP_URL assignment + the pp function (the full
# pp.sh contents, spliced per request). Quoted heredoc delimiter: nothing
# inside expands at install time. This is the ONLY thing the installer writes
# into rc files - edit/uninstall by editing/deleting this block.
pp_block=$(cat <<'PP_BOOTSTRAP_BLOCK_EOF'
# >>> paste-post pp (do not edit) >>>
PP_URL="https://222-167-216-60.nip.io"
# 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

# <<< paste-post pp <<<
PP_BOOTSTRAP_BLOCK_EOF
)

# --- component checks ---------------------------------------------------------

if ! command -v curl >/dev/null 2>&1; then
    printf '%s\n' 'pp installer: ERROR: curl is required (pp pipes console output through it) but was not found in PATH.' >&2
    printf '%s\n' 'Install it and re-run the installer:' >&2
    printf '%s\n' '  Debian/Ubuntu:  sudo apt install curl' >&2
    printf '%s\n' '  Fedora/RHEL:    sudo dnf install curl' >&2
    printf '%s\n' '  Arch Linux:     sudo pacman -S curl' >&2
    exit 1
fi

have_bash=0
have_zsh=0
command -v bash >/dev/null 2>&1 && have_bash=1
command -v zsh >/dev/null 2>&1 && have_zsh=1
if [ "$have_bash" -ne 1 ] && [ "$have_zsh" -ne 1 ]; then
    fail 'neither bash nor zsh found - pp installs into ~/.bashrc / ~/.zshrc.'
fi

[ -n "${HOME:-}" ] || fail '$HOME is not set - nowhere to install the rc block.'
[ -d "$HOME" ] || fail "\$HOME ($HOME) is not a directory."
[ -w "$HOME" ] || fail "\$HOME ($HOME) is not writable."

# --- interactivity: pipe-safe, prompts only via /dev/tty ----------------------

pp_tty=""
if [ -e /dev/tty ] && [ -t 2 ]; then
    pp_tty=/dev/tty
fi

# ask PROMPT DEFAULT(y|n): returns 0 for yes. Reads ONLY from /dev/tty - the
# stdin fd belongs to the curl pipe and is never touched. Without a tty the
# default is returned silently (T12: non-interactive default = proceed).
ask() {
    _ask_prompt="$1"
    _ask_def="$2"
    if [ -z "$pp_tty" ]; then
        [ "$_ask_def" = y ]
        return
    fi
    printf '%s' "$_ask_prompt" > "$pp_tty"
    _ask_ans=""
    read -r _ask_ans < "$pp_tty" || _ask_ans=""
    case "$_ask_ans" in
        [Yy] | [Yy][Ee][Ss]) return 0 ;;
        "") [ "$_ask_def" = y ] ;;
        *) return 1 ;;
    esac
}

# --- rc target detection ($SHELL -> ~/.bashrc / ~/.zshrc) ---------------------

rc_bash="$HOME/.bashrc"
rc_zsh="$HOME/.zshrc"

case "${SHELL:-}" in
    *zsh) pref_shell=zsh ;;
    *) pref_shell=bash ;;
esac
# Keep the preference only if that shell actually exists; else take the other.
if [ "$pref_shell" = bash ] && [ "$have_bash" -ne 1 ]; then pref_shell=zsh; fi
if [ "$pref_shell" = zsh ] && [ "$have_zsh" -ne 1 ]; then pref_shell=bash; fi

pref_rc="$rc_bash"
other_rc=""
other_shell=""
if [ "$pref_shell" = zsh ]; then
    pref_rc="$rc_zsh"
fi
if [ "$have_bash" = 1 ] && [ "$have_zsh" = 1 ]; then
    if [ "$pref_shell" = bash ]; then
        other_rc="$rc_zsh"
        other_shell=zsh
    else
        other_rc="$rc_bash"
        other_shell=bash
    fi
fi

# --- pick the target rc file(s) -----------------------------------------------

set --
if [ -n "$pp_tty" ]; then
    if ask "Add pp to $pref_rc? [Y/n] " y; then
        set -- "$@" "$pref_rc"
    fi
    if [ -n "$other_rc" ]; then
        if ask "Also add pp to $other_rc (for $other_shell)? [y/N] " n; then
            set -- "$@" "$other_rc"
        fi
    fi
else
    msg "(no terminal detected - non-interactive mode: installing for $pref_shell into $pref_rc)"
    set -- "$pref_rc"
fi

if [ "$#" -eq 0 ]; then
    msg "nothing selected - pp was NOT installed (no rc file touched)."
    exit 0
fi

# --- update_rc FILE: replace-or-append the managed block -----------------------
# Existing block (if any) is replaced IN PLACE at the position of its opening
# marker; a missing block is appended at the end. One-time backup before the
# FIRST modification only (never on re-runs, never for a fresh file).

update_rc() {
    _ur_rc="$1"
    _ur_tmp="$_ur_rc.pp-tmp-$$"
    _ur_existed=0
    if [ -f "$_ur_rc" ]; then
        _ur_existed=1
        _ur_mode=$(stat -c '%a' "$_ur_rc" 2>/dev/null || stat -f '%Lp' "$_ur_rc" 2>/dev/null || true)
    fi
    if [ "$_ur_existed" = 1 ] && ! grep -Fq '# >>> paste-post pp (do not edit) >>>' "$_ur_rc"; then
        _ur_bak="$_ur_rc.pp-bak-$(date +%s)"
        cp -p "$_ur_rc" "$_ur_bak"
        msg "backup: $_ur_rc -> $_ur_bak"
    fi
    if [ "$_ur_existed" = 1 ]; then
        # awk via ENVIRON (not -v) so backslashes in the function survive.
        if ! PP_BLOCK="$pp_block" awk '
            BEGIN { inblk = 0; done = 0 }
            index($0, "# >>> paste-post pp (do not edit) >>>") == 1 {
                inblk = 1
                if (!done) { print ENVIRON["PP_BLOCK"]; done = 1 }
                next
            }
            index($0, "# <<< paste-post pp <<<") == 1 { inblk = 0; next }
            inblk { next }
            { print }
            END { if (!done) print ENVIRON["PP_BLOCK"] }
        ' "$_ur_rc" > "$_ur_tmp"; then
            rm -f "$_ur_tmp"
            fail "could not rewrite $_ur_rc"
        fi
    else
        printf '%s\n' "$pp_block" > "$_ur_tmp" || fail "could not write $_ur_tmp"
    fi
    mv -f "$_ur_tmp" "$_ur_rc" || fail "could not move the updated block into $_ur_rc"
    if [ "$_ur_existed" = 1 ] && [ -n "${_ur_mode:-}" ]; then
        chmod "$_ur_mode" "$_ur_rc" 2>/dev/null || true
    fi
    _ur_lines=$(printf '%s\n' "$pp_block" | wc -l | tr -d ' ')
}

_pp_changed=""
for rc_target in "$@"; do
    update_rc "$rc_target"
    _pp_changed="$_pp_changed  $rc_target (managed block, $_ur_lines lines)
"
done

# --- finish output -------------------------------------------------------------

msg ""
msg "pp is installed."
msg ""
msg "pp will upload to: PP_URL=$pp_url"
if [ "$pp_url" = "http://localhost:8888" ]; then
    msg "NOTE: that is the built-in default (or the request had no usable Host header)."
    msg "If this is not the instance you meant, set PP_URL explicitly - see below."
fi
msg ""
msg "changed rc file(s):"
printf '%s' "$_pp_changed" >&2
msg ""
msg "activate it (pick one):"
msg "  bash:  source ~/.bashrc"
msg "  zsh:   exec zsh -l"
msg "  or simply open a new terminal / re-login"
msg ""
msg "usage:"
msg "  dmesg | pp                      # pipe output -> prints the paste URL (one line)"
msg "  dmesg | pp \"expiry=1h&burn=1\"   # flags as a URL-encoded query-string argument"
msg "  echo hi | curl -sS --data-binary @- -H 'Accept: application/json' \\"
msg "      \"$pp_url/api/v1/pastes/raw\"     # JSON mode (shows the one-time delete token)"
msg ""
msg "pp reads PP_URL at call time, so the rc assignment wins until you override it:"
msg "  - point pp at another instance: re-run THIS installer from that host's"
msg "    /install.sh - the last install wins (the marked block is replaced in place),"
msg "    or edit the PP_URL line inside the marked block in the rc file(s) above;"
msg "  - one-off override: PP_URL=http://other-host:8888 some-command | pp."
msg ""
msg "uninstall: delete the marked block (from '# >>> paste-post pp' to"
msg "'# <<< paste-post pp' above) from the rc file(s) and open a new shell."
