#!/usr/bin/env bash
#
# _office-smoke-lib.sh  -  shared by the office route smokes: a synthetic
# office seeded into a temporary directory, one contract-server started on it,
# and a request helper that can send any Host, Origin or Authorization.
#
# Repo layout only: the seed lives under test/fixtures, which an install does
# not carry, so a smoke sourcing this skips itself when that file is absent.
#
# Usage (from a smoke in pipeline/scripts/):
#   . "$(dirname "${BASH_SOURCE[0]}")/_office-smoke-lib.sh"
#   office_start            # sets OFFICE_PORT, OFFICE_TOKEN, OFFICE_SECRET, ...
#   office_req GET /v1/activity [header...]   # body in $OFFICE_BODY, status echoed
#   office_stop             # also run by the EXIT trap

OFFICE_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OFFICE_ROOT="$(cd "$OFFICE_LIB_DIR/../.." && pwd)"
OFFICE_SEED="$OFFICE_ROOT/test/fixtures/office-seed.mjs"
OFFICE_SERVER="$OFFICE_LIB_DIR/contract-server.mjs"
OFFICE_TMP=""
OFFICE_PID=""

office_available() { [ -f "$OFFICE_SEED" ] && command -v curl >/dev/null 2>&1; }

office_stop() {
  if [ -n "$OFFICE_PID" ]; then
    kill -TERM "$OFFICE_PID" 2>/dev/null
    wait "$OFFICE_PID" 2>/dev/null
    OFFICE_PID=""
  fi
  if [ -n "$OFFICE_TMP" ] && [ -d "$OFFICE_TMP" ]; then
    find "$OFFICE_TMP" -depth -mindepth 1 -delete 2>/dev/null
    rmdir "$OFFICE_TMP" 2>/dev/null
  fi
}

# office_json <file> <expression on o>  -  one value out of a JSON file.
office_json() {
  node -e 'const o=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));const v=(new Function("o","return "+process.argv[2]))(o);process.stdout.write(typeof v==="string"?v:JSON.stringify(v))' "$1" "$2"
}

office_start() {
  OFFICE_TMP="$(mktemp -d "${TMPDIR:-/tmp}/office-smoke.XXXXXX")"
  trap office_stop EXIT
  node "$OFFICE_SEED" "$OFFICE_TMP/office" > "$OFFICE_TMP/seed.json" || return 1
  OFFICE_SECRET="$(office_json "$OFFICE_TMP/seed.json" o.secret)"
  OFFICE_BLOB="$(office_json "$OFFICE_TMP/seed.json" o.blob)"
  OFFICE_THINKING="$(office_json "$OFFICE_TMP/seed.json" o.thinking)"
  OFFICE_SESSION="$(office_json "$OFFICE_TMP/seed.json" o.session)"
  node -e '
    const s = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"));
    for (const [k, v] of Object.entries(s.env)) console.log(`export ${k}=${JSON.stringify(v)}`);
  ' "$OFFICE_TMP/seed.json" > "$OFFICE_TMP/env.sh"
  # shellcheck disable=SC1091
  . "$OFFICE_TMP/env.sh"
  node "$OFFICE_SERVER" --port 0 --print-token --allow-origin "http://127.0.0.1:5173" \
    > "$OFFICE_TMP/ready" 2> "$OFFICE_TMP/server.err" &
  OFFICE_PID=$!
  local i=0
  while [ ! -s "$OFFICE_TMP/ready" ] && [ "$i" -lt 100 ]; do
    sleep 0.1
    i=$((i + 1))
  done
  [ -s "$OFFICE_TMP/ready" ] || return 1
  OFFICE_PORT="$(office_json "$OFFICE_TMP/ready" o.port)"
  OFFICE_TOKEN="$(office_json "$OFFICE_TMP/ready" o.token)"
  return 0
}

# office_req METHOD PATH [header...]
# Sends Host 127.0.0.1:<port> and the bearer token unless a header overrides
# them (pass "Host: x" or "Authorization: none" to change them). Prints the
# status; the body is left in $OFFICE_TMP/body. The URL and every header go
# to curl through a 0600 config file, never through argv, so the token (and
# the token-shaped values the attack checks send) stay off the process list.
office_req() {
  local method="$1" path="$2"
  shift 2
  local host="Host: 127.0.0.1:$OFFICE_PORT" auth="Authorization: Bearer $OFFICE_TOKEN"
  local cfg="$OFFICE_TMP/curl.cfg"
  local h
  : > "$cfg"
  chmod 600 "$cfg"
  for h in "$@"; do
    case "$h" in
      Host:*) host="$h" ;;
      "Authorization: none") auth="" ;;
      Authorization:*) auth="$h" ;;
      *) office_cfg_line header "$h" >> "$cfg" ;;
    esac
  done
  office_cfg_line header "$host" >> "$cfg"
  [ -n "$auth" ] && office_cfg_line header "$auth" >> "$cfg"
  if [ -n "${OFFICE_DATA:-}" ]; then
    office_cfg_line header "Content-Type: application/json" >> "$cfg"
    printf '%s' "$OFFICE_DATA" > "$OFFICE_TMP/data.json"
    office_cfg_line data-binary "@$OFFICE_TMP/data.json" >> "$cfg"
  fi
  office_cfg_line url "http://127.0.0.1:$OFFICE_PORT$path" >> "$cfg"
  curl -s -m "${OFFICE_MAX_TIME:-10}" -o "$OFFICE_TMP/body" -w '%{http_code}' -X "$method" -K "$cfg"
}

# office_cfg_line KEY VALUE  -  one curl config line, the value quoted.
office_cfg_line() {
  local v="${2//\\/\\\\}"
  v="${v//\"/\\\"}"
  printf '%s = "%s"\n' "$1" "$v"
}

# office_call METHOD PATH [headers...]  -  office_req without a subshell:
# sets OFFICE_STATUS and OFFICE_BODY in the caller.
office_call() {
  OFFICE_STATUS="$(office_req "$@")"
  OFFICE_BODY="$(cat "$OFFICE_TMP/body" 2>/dev/null)"
}
