#!/bin/sh

Wait_for_service ()
{
	LOOP="0"
	LIMIT="10"

	echo -n "Waiting for service to be up and running "

	while ! vtysh -c "show version" 2>/dev/null | grep -Eq "^FRRouting"
	do
		echo -n "."

		LOOP="$((${LOOP} + 1))"

		if [ "${LOOP}" -ge "${LIMIT}" ]
		then
			echo "Failed to start service after ${LIMIT}s, giving up."
			return 1
		fi

		sleep 1s
	done

	echo " done."
}

cleanup() {
    result=$?
    set +e
    if [ "$result" -ne 0 ]; then
        echo "### Something failed, showing logs"
        echo
        echo "### Last 100 lines of syslog:"
        tail -n 100 /var/log/syslog
        echo
        for f in /var/log/frr/*.log; do
            if [ -f "$f" ]; then
                echo "### Last 100 lines of $f:"
                tail -n 100 "$f"
                echo
            fi
        done
        echo "### ps output:"
        ps fauxwZ
        echo
        echo "### Last 100 dmesg lines:"
        dmesg -T | tail -n 100 || :
    else
        echo "### ALL TESTS PASSED"
    fi
}
