#!/bin/sh
# Report that this install happened, and by which channel. Nothing else.
#
# Sends {product, version, source} to the distribution endpoint — no install id, no
# hostname, no file path, no username. It exists because a registry download count
# cannot distinguish a person running `npm i -g` from a CI job pulling a dependency,
# and we would rather measure the real number than guess at it.
#
# It only ever runs for a deliberate global install. The selector's postinstall is
# gated on npm_config_global=true, so a dependency or CI install never reaches this
# file at all. That gate is the filter; this script only records which channel.
#
# Off with either, and nothing is sent:
#   COGITO_USAGE_REPORT=0   the same switch the daemon's own reporters honor
#   DO_NOT_TRACK=1          the cross-vendor standard
#
# It cannot break an install. It is a separate process invoked with `|| true` after the
# install has already succeeded, is capped at two seconds, and discards every failure.
# This is required, not merely polite: the npm artifact contract carries an
# `offline-install` guarantee, so a stranger with no network must install identically.
set -u

[ "${COGITO_USAGE_REPORT:-1}" != "0" ] || exit 0
[ "${DO_NOT_TRACK:-0}" != "1" ] || exit 0
command -v curl >/dev/null 2>&1 || exit 0

base="${COGITO_TELEMETRY_BASE:-https://cogito.cv}"
# Interpolated into JSON, so keep it to version characters. A quote or newline from an
# unexpected build would otherwise produce a malformed body.
version=$(printf '%s' "${1:-}" | tr -cd 'A-Za-z0-9._+-' | cut -c1-32)

curl -fsS -m 2 -X POST "$base/api/distribution/download" \
  -H 'Content-Type: application/json' \
  -d "{\"product\":\"cogitod\",\"version\":\"${version:-unknown}\",\"source\":\"npm-postinstall\"}" \
  >/dev/null 2>&1 || true

exit 0
