#!/bin/sh
set -eu
. "$(git rev-parse --show-toplevel)/ci/msrv.sh"

step() {
    >&2 echo
    >&2 echo ">>> $*"
}

if ! command -v cargo > /dev/null 2>&1; then
    curl -o ~/rustup-init https://static.rust-lang.org/rustup/dist/x86_64-unknown-linux-gnu/rustup-init
    chmod +x ~/rustup-init
    ~/rustup-init -y --default-toolchain $msrv
    . ~/.cargo/env
fi

export RUSTFLAGS="${RUSTFLAGS-}${RUSTFLAGS+ }--cfg ci_"
export RUSTDOCFLAGS="${RUSTDOCFLAGS-}${RUSTDOCFLAGS+ }--cfg ci_"

step 'check formatting'
( set -x; cargo +$msrv fmt --all -- --check )

step 'run tests (no features)'
( set -x; cargo +$msrv test -p nonymous --no-default-features )

step 'run tests (alloc feature only)'
( set -x; cargo +$msrv test -p nonymous --no-default-features --features alloc )

step 'run tests (all features for stable rust)'
( set -x; cargo +$msrv test --workspace --features _all_features_for_stable_rust --all-targets )

step 'run doc tests (all features for stable rust)'
( set -x; cargo +$msrv test --workspace --features _all_features_for_stable_rust --doc )

step 'build docs (all features for stable rust)'
( set -x; cargo +$msrv doc --workspace --features _all_features_for_stable_rust --no-deps --document-private-items )

step 'run tests (all features)'
( set -x; RUSTC_BOOTSTRAP=1 cargo +$msrv test --workspace --all-features --all-targets )

step 'run doc tests (all features)'
( set -x; RUSTC_BOOTSTRAP=1 cargo +$msrv test --workspace --all-features --doc )

step 'build docs (all features)'
( set -x; RUSTC_BOOTSTRAP=1 cargo +$msrv doc --workspace --all-features --no-deps --document-private-items )

step 'check `#![no_std]` compatibility'
( set -x; cd nonono; RUSTC_BOOTSTRAP=1 cargo +$msrv run )

step 'test `bore --decode`'
( set -x;
printf '\0\0\0\0\0\0\0\0\0\0\0\0' \
| cargo +$msrv run -p bore -- --decode \
| grep -q ';; NoError #0 Query 0 0 0 0 flags'
)

step 'test `bore --show-resolvers`'
( set -x;
cargo +$msrv run -p bore -- --show-resolvers \
| grep -q 'effective resolver order (no --port):'
)

step 'test `dynrdns` example'
( set -x;
target_dir=${CARGO_TARGET_DIR-target}
cargo +$msrv build -p bore
cargo +$msrv build --example dynrdns --features _all_features_for_stable_rust
"$target_dir/debug/bore" --encode -x 10.42.69.0 \
| "$target_dir/debug/examples/dynrdns" \
| "$target_dir/debug/bore" --decode \
| fgrep -q '0.69.42.10.in-addr.arpa. 0 IN PTR dyn-10-42-69-0.isp.example.'
)

# TODO code coverage
