#!/usr/bin/env bash
#
# Script to benchmark syd-tor(1)
# Requirements: microsocks, ss, syd, syd-tor.
#
# Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
# SPDX-License-Identifier: GPL-3.0

# First argument may be one of 100M, 1G, 10G, 100G, 1000G.
case "${1}" in
100M|1G|10G|100G|1000G)
    URL="http://speedtest.belwue.net/${1}";;
'')
    URL="http://speedtest.belwue.net/100M";;
*)
    echo >&2 "First argument must be one of 100M, 1G, 100G, or 1000G."
    exit 22 # EINVAL
esac
set -ex

# Start microsocks on localhost with ephemeral port.
microsocks -q -i 127.0.0.1 -p 0 &
ms_pid=$!
trap "kill -9 ${ms_pid}" EXIT INT TERM

# Wait for microsocks to bind and extract the port.
until ss -lnpt | grep -q "pid=${ms_pid}"; do sleep 0.05; done
ms_port=$(ss -lnpt | awk -v pid="$ms_pid" '$0 ~ "pid="pid { for(i=1;i<=NF;i++) if($i ~ /127\.0\.0\.1:[0-9]+/) { print $i; exit } }' | sed 's/.*://')

# Run the comparison with hyperfine.
curl_cmd=( curl --socks5-hostname 127.0.0.1:${ms_port} -s -o/dev/null "${URL}" )
csyd_cmd=(
    syd -poff -munshare/user:1 -msandbox/proxy:on -mproxy/ext/port:${ms_port}
    curl --socks5-hostname 127.0.0.1:9050 -s -o/dev/null "${URL}"
)
hyperfine -- "${curl_cmd[*]}" "${csyd_cmd[*]}"
