#!/usr/bin/env bash
# Applies fix.patch to a copy of a FIT C++ SDK checkout and runs prove.sh on
# the copy, so the fix is shown to end the over-read without touching the
# checkout.
#
#   patch.sh [sdk-dir] [out-dir]   the SDK's root, holding src/ (this tree's
#                                  fit-cpp-sdk/ when none is given); the
#                                  patched copy is kept in out-dir when given
#
# Exits 0 when the patched SDK reads short-field.fit cleanly.
set -uo pipefail

here="$(cd "$(dirname "$0")" && pwd)"
sdk="$(cd "${1:-$here/../../fit-cpp-sdk}" && pwd)"
out="${2:-}"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT

mkdir -p "$work/sdk"
cp -r "$sdk/src" "$work/sdk/src"
# A Windows checkout has CRLF endings; the patch is made against the
# repository's LF.
find "$work/sdk/src" -type f \( -name '*.cpp' -o -name '*.hpp' \) -exec sed -i 's/\r$//' {} +
if ! patch -d "$work/sdk" -p1 --quiet < "$here/fix.patch"; then
    echo "fix.patch does not apply to $sdk"
    exit 2
fi
echo "fix.patch applied to a copy of $sdk"
if [ -n "$out" ]; then
    mkdir -p "$out"
    cp -r "$work/sdk/src" "$out/"
    echo "the patched src/ is in $out"
fi

"$here/prove.sh" "$work/sdk"
case $? in
    1) exit 0 ;;
    0) echo "The patched SDK still reads past a buffer."; exit 1 ;;
    *) exit 2 ;;
esac
