# shellcheck shell=sh
# included by test scripts

SKIP=77

create_some_files() {
mkdir -p somefiles/topdir/dir1/dir2/dir3

c=1
while [ "$c" -lt 25 ]
do
   touch "somefiles/topdir/dir1/dir2/dir3/$c"
   c=$((c + 1))
done

touch somefiles/read_only_file
chmod ugo-w somefiles/read_only_file
}

cmp_substr () {
  if [ -z "$1" ] || [ -z "$2" ]; then
    return 1
  fi
  [ -z "${1##*"$2"*}" ]
  return $?
}

if test -z "${MESON_BUILD_ROOT}" || test -z "${RMW_FAKE_HOME}"; then
  echo "This script is used by the build system. Use 'meson test'"
  echo "from the builddir."
  exit 1
fi

RMW_FAKE_HOME="${RMW_FAKE_HOME}/$(basename "$0")_dir"
HOME="${RMW_FAKE_HOME}"
XDG_DATA_HOME="${RMW_FAKE_HOME}/.local/share"
XDG_CONFIG_HOME="${RMW_FAKE_HOME}/.config"
export HOME XDG_DATA_HOME XDG_CONFIG_HOME
# shellcheck disable=SC2034
CONFIG="${MESON_SOURCE_ROOT}/test/conf/rmw.testrc"
# shellcheck disable=SC2034
ALT_CONFIG="${MESON_SOURCE_ROOT}/test/conf/rmw.alt.testrc"
# shellcheck disable=SC2034
PURGE_DISABLED_CONFIG="${MESON_SOURCE_ROOT}/test/conf/rmw.purge_disabled.testrc"
export BIN_DIR="${MESON_BUILD_ROOT}"

export RMW_FAKE_HOME

if [ -e "${RMW_FAKE_HOME}" ]; then
  rm -rf "${RMW_FAKE_HOME}"
fi

# shellcheck disable=SC2034
RMW_TEST_CMD_STRING="${BIN_DIR}/rmw -c $CONFIG"

# shellcheck disable=SC2034
PRIMARY_WASTE_DIR="${RMW_FAKE_HOME}/.Waste"

# shellcheck disable=SC2034
RMW_ALT_TEST_CMD_STRING="${BIN_DIR}/rmw -c ${ALT_CONFIG}"
# shellcheck disable=SC2034
RMW_PURGE_DISABLED_CMD="${BIN_DIR}/rmw -c ${PURGE_DISABLED_CONFIG}"
# shellcheck disable=SC2034
SEPARATOR="\n\n--- "

# strace needs ptrace, which QEMU user-mode emulation does not implement (the
# arm64 Debian build runs that way) and which some hardened containers block.
# meson cannot see that, so probe it here and drop the assertions if it fails.
if [ -n "$STRACE" ] && ! "$STRACE" -o /dev/null true 2>/dev/null; then
  echo "COMMON: ptrace unavailable, syscall assertions will be skipped"
  STRACE=""
fi

strace_check() {
  # Usage: strace_check [-t trace_filter] pattern cmd [args...]
  # Runs cmd under strace and asserts pattern appears in the syscall trace.
  # -t overrides the default trace filter (%file); use "ioctl" for FICLONE checks.
  # $STRACE is set only when strace exists and sanitizers are off; see test/meson.build.
  _trace="%file"
  if [ "$1" = "-t" ]; then
    _trace="$2"
    shift 2
  fi
  _pattern="$1"
  shift
  if [ -z "$STRACE" ]; then
    # Say so in the test log; a dropped assertion should not be silent.
    echo "strace_check: STRACE is unset, syscall assertion skipped"
    "$@"
    return
  fi
  _strace_out=$(mktemp)
  "$STRACE" -o "$_strace_out" -e "trace=$_trace" "$@"
  grep -q "$_pattern" "$_strace_out"
  rm -f "$_strace_out"
}
