#!/bin/bash
#
# Run NIX crate tests under Syd.
#
# Copyright 2025 Ali Polatel <alip@chesswob.org>
#
# SPDX-License-Identifier: GPL-3.0

# Make sure we don't trigger TPE.
umask 077

# Enable coredumps.
ulimit -c unlimited

# Force TTY output.
export SYD_FORCE_TTY=YesPlease

# Enable path hiding and ioctl sandboxing for wider coverage.
# This works because NIX profile includes the PALUDIS profile.
export SYD_PALUDIS_LPATH=1
export SYD_PALUDIS_IOCTL=1

# Timeout is 20 minutes per-test unless otherwise specified.
SYD_TEST_TIMEOUT=${SYD_TEST_TIMEOUT:-20m}

export SYD_LOG=${SYD_LOG:-notice}
SYD="${CARGO_BIN_EXE_syd:-syd}"

edo() {
    echo >&2 "-- $*"
    "$@"
}

run_test() {
    [[ -n "${SYD_TEST_DMESG}" ]] && sudo dmesg -C

    "${SYD}" -pnix -- cargo test --release 2>&1
    r=$?

    if [[ $r == 0 ]]; then
        return 0
    fi

    if [[ -n "${SYD_TEST_DMESG}" ]]; then
        echo '--8<-- KERNEL LOG BEGIN -->8--'
        sudo dmesg
        echo '-->8-- KERNEL LOG END   --8<--'
    fi

    return $r
}

arg_depth='--depth 1'
if [[ -n "${NIX_HEAD}" ]]; then
    arg_depth=
fi

set -ex
DIR="$(mktemp -d syd-nix.XXXXX)"
set +e
pushd "${DIR}"
git clone ${arg_depth} --recursive https://github.com/nix-rust/nix.git nix.git || exit 0
pushd nix.git
if [[ -n "${NIX_HEAD}" ]]; then
    git checkout "${NIX__HEAD}" || exit 127
fi
git rev-parse HEAD
set +x

run_test
exit $?
