#!/bin/bash
# For debugging proxy.rs

set -euo pipefail
set -x

export RUST_LOG=innisfree=trace
export OPENSSL_STATIC=1

# Declare TCP port to check over
local_port="8080"

# Make sure anything that wasn't cleaned up is killed
netstat -lnp | grep -iF "$local_port" | perl -lanE 'say $F[-1]' | grep -oP '^\d+' \
    | xargs -d '\n' -r kill || true

# Prepare test dir
dst_dir="$(mktemp -d)"
test_string="Hello, world! $(uuid)"
echo "$test_string" > "${dst_dir}/index.html"

# Make sure to clean up afterwards
cleanup() {
    # disable 'set -e' to ensure all these cleanup tasks run
    set +e
    jobs -p | xargs -r kill
    rm -rf "$dst_dir"
    reset
}
trap 'cleanup' EXIT

# We don't use 'cargo run' because we want SIGINT to tear down the process.
# Wrapping innisfree in 'cargo run' may interfere with signal handling.
cargo build
sudo setcap CAP_NET_BIND_SERVICE,CAP_NET_ADMIN=+ep ./target/debug/innisfree
./target/debug/innisfree up -p "$local_port" &
sleep 90

# Host webroot containing test string
python3 -m http.server --directory "$dst_dir" "$local_port" &
sleep 1

# Make sure we find the unique test string,
# over both localhost (as control) and remote IP.
curl -I "http://localhost:${local_port}"
result_string="$(curl -s --connect-timeout 3 --max-time 5 "http://$(cargo run -- ip):${local_port}")"
result=0
if [[ "$test_string" != "$result_string" ]] ; then
    echo "ERROR: Failed to find test string: '$test_string'" >&2
    jobs -p | xargs -r kill
    result=1
else
    echo "SUCCESS: Found test string: '$test_string'" >&2
    echo "Cleaning up..." >&2
    # use SIGINT to kill because I haven't figured out how to catch other signals
    jobs -p | xargs -r kill -s SIGINT
    sleep 5
    result=0
fi

cleanup
wait
exit "$result"
