#!/bin/sh
# Downloads perfetto's trace_processor_shell, matching the SDK version vendored
# in deps/perfetto. The trace events tests read back the binary traces that
# perfetto builds write through this tool.
set -e

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
version=$(cat "$script_dir/../../deps/perfetto/VERSION")
trace_processor="${1:-$script_dir/trace_processor_shell}"

# Perfetto names its release archives <os>-<arch>, which does not match uname.
case "$(uname -s)" in
  Darwin) os=mac ;;
  Linux) os=linux ;;
  *) echo "No perfetto release for $(uname -s)" >&2; exit 1 ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) echo "No perfetto release for $(uname -m)" >&2; exit 1 ;;
esac

url="https://github.com/google/perfetto/releases/download/v$version/$os-$arch.zip"
archive=$(mktemp)

rm -f "$trace_processor"
echo "Downloading $url"
curl -sSfL -o "$archive" "$url"
unzip -q -j -o "$archive" '*/trace_processor_shell' -d "$script_dir"
rm -f "$archive"
chmod +x "$trace_processor"
# The archive carries the release's own mtime. Make decides whether the tool is
# current by comparing it against deps/perfetto/VERSION, so it has to come out
# newer than the version file it was downloaded for.
touch "$trace_processor"
