#!/bin/bash

set -euo pipefail

cd "$(dirname "$0")"/..

function eprintln() {
  >&2 echo "$1"
}

pushd ..
eprintln "Installing mdbook-admonish (system)"
cargo install --path . --force
popd

eprintln "Installing mdbook-admonish (book)"
mdbook-admonish install .

eprintln "Verifying generated book config"
set +e
diff -u \
  "expected/book.toml" \
  "./book.toml"
DIFF_RESULT=$?
set -e

if [ "$DIFF_RESULT" != 0 ]; then
  eprintln ""
  eprintln "error: generated book config was different than expected"
  eprintln ""
  eprintln "error: If you expected the output to change, run:"
  eprintln "cp ./integration/book.toml ./integration/expected/book.toml"
  eprintln "and commit the result"
  exit 1
fi

eprintln "Generating custom CSS (book)"
mdbook-admonish generate-custom mdbook-admonish-custom.css

eprintln "Verifying generated book custom css"
set +e
diff -u \
  "expected/mdbook-admonish-custom.css" \
  "./mdbook-admonish-custom.css"
DIFF_RESULT=$?
set -e

if [ "$DIFF_RESULT" != 0 ]; then
  eprintln ""
  eprintln "error: generated custom css was different than expected"
  eprintln ""
  eprintln "error: If you expected the output to change, run:"
  eprintln "cp ./integration/mdbook-admonish-custom.css ./integration/expected/mdbook-admonish-custom.css"
  eprintln "and commit the result"
  exit 1
fi

eprintln "Building mdbook"
mdbook build


eprintln "Verifying generated html"
set +e
diff -u \
  "expected/chapter_1_main.html" \
  <(./scripts/get-snapshot)
DIFF_RESULT=$?
set -e

if [ "$DIFF_RESULT" != 0 ]; then
  eprintln ""
  eprintln "error: generated html was different than expected"
  eprintln ""
  eprintln "error: If you expected the output to change, run:"
  eprintln "./integration/scripts/update-snapshot"
  eprintln "and commit the result"
  exit 1
fi

eprintln "Verifying mdbook test runs doctests"
set +e
TEST_RESULT="$(mdbook test 2>&1 | grep "1 passed; 1 failed")"
set -e

if [[ "$TEST_RESULT" != "test result: FAILED. 1 passed; 1 failed;"* ]]; then
  eprintln ""
  eprintln "error: mdbook test did not complete as expected"
  eprintln ""
  eprintln "Full output:"
  mdbook test
  exit 1
fi
