#!/bin/sh
# Runs the app-bundled Postman CLI on the desktop app's own Electron binary.
#
# Staged into the CLI payload as <payload>/bin/postman and put on the in-app
# terminal's PATH. The Electron binary comes from POSTMAN_CLI_ELECTRON, set by
# the terminal provider when it spawns the PTY.

set -e

self=$0

# Resolve symlinks by hand — `readlink -f` is not portable in /bin/sh. Capped so a
# symlink cycle fails the command instead of hanging the terminal it was run from.
hops=0
while [ -L "$self" ]; do
  hops=$((hops + 1))
  if [ "$hops" -gt 32 ]; then
    echo "postman: too many symlinks resolving $0" >&2
    exit 1
  fi

  link=$(readlink "$self")
  case $link in
    /*) self=$link ;;
    *) self=$(dirname "$self")/$link ;;
  esac
done

bin_dir=$(cd "$(dirname "$self")" && pwd -P)
root=$(dirname "$bin_dir")
bundle="$root/postman.bundled.js"

if [ ! -f "$bundle" ]; then
  echo "postman: bundled CLI not found at $bundle" >&2
  exit 1
fi

if [ -z "$POSTMAN_CLI_ELECTRON" ]; then
  echo "postman: POSTMAN_CLI_ELECTRON is not set — the app-bundled CLI only runs in Postman's terminal." >&2
  exit 1
fi

export ELECTRON_RUN_AS_NODE=1
export POSTMAN_CLI_BUNDLED_ROOT="$root"

# Electron reads the OS trust store, Node does not, so the app's CA setting has to be
# handed to the CLI explicitly. Scoped to this process rather than the whole terminal.
if [ -n "$POSTMAN_CLI_CA_CERTS" ]; then
  export NODE_EXTRA_CA_CERTS="$POSTMAN_CLI_CA_CERTS"
fi

exec "$POSTMAN_CLI_ELECTRON" "$bundle" "$@"
