#!/bin/sh

test_num=0
fail=0

# TAP output goes to fd 7, which is our original stdout
exec 7>&1
# Other stdout goes to our original stderr
exec >&2

require_apt_jessie () {
    mirror="$(perl -ne 'print $1 if m{^deb\s+http://([-\w.:]+)/debian/?\s}' /etc/apt/sources.list /etc/apt/sources.list.d/*)"
    if [ -n "$mirror" ]; then
        echo >> /etc/apt/sources.list
        echo "deb http://$mirror/debian jessie main" >> /etc/apt/sources.list
    else
        echo "1..0 # SKIP - unable to guess how to set up an apt source for jessie" >&7
    fi

    require_apt
}

require_apt () {
    if ! apt-get -y update; then
        echo "1..0 # SKIP - apt not configured?" >&7
        exit 0
    fi

    if ! apt-get -y install hello; then
        echo "1..0 # SKIP - apt not configured?" >&7
        exit 0
    fi
}

require_systemd () {
    if ! [ -d /run/systemd/system ]; then
        echo "1..0 # SKIP - init is not systemd, cannot use libnss-resolve" >&7
        exit 0
    fi
}

assert_succeeds () {
    assert_status 0 "$@"
}

assert_status () {
    local expected="$1"
    local e

    shift
    test_num=$(( $test_num + 1 ))

    echo "# $*"
    if "$@"; then
        if [ "x$expected" = x0 ]; then
            echo "ok $test_num - “$*”" >&7
        else
            echo "not ok $test_num - “$*” succeeded but should have failed" >&7
            fail=1
        fi
    else
        e="$?"
        if [ "x$expected" = "x$e" ] || [ "x$expected" = xfailure ]; then
            echo "ok $test_num - “$*” failed with status $e as expected" >&7
        else
            echo "not ok $test_num - “$*” expected status $expected, got $e" >&7
            fail=1
        fi
    fi
}

assert_output () {
    local expected="$1"
    shift
    local really

    test_num=$(( $test_num + 1 ))
    echo "# $*"

    if really="$("$@")"; then
        if [ "x$expected" = "x$really" ]; then
            echo "ok $test_num - “$*” returned “$really” as expected" >&7
        else
            echo "not ok $test_num - expected “$*” to output “$*”, got “$really”" >&7
            fail=1
        fi
    else
        e="$?"
        echo "not ok $test_num - “$*” failed with exit status $e" >&7
        fail=1
    fi
}

assert_hosts () {
    local expected="$1"
    local really="$(perl -ne 'print if /^hosts:/' /etc/nsswitch.conf)"
    test_num=$(( $test_num + 1 ))

    if [ "x$expected" = "x$really" ]; then
        echo "ok $test_num - “$really” in nsswitch.conf as expected" >&7
    else
        echo "not ok $test_num - expected “$expected” in nsswitch.conf, got “$really”" >&7
        fail=1
    fi
}

get_resolve_rune () {
    perl -ne 'print $1 if /^hosts:.*\s(resolve(?:\s+\[!?[A-Z]+=[a-z]+\])?)/' /etc/nsswitch.conf
}

finish () {
    echo "1..$test_num" >&7
    exit "$fail"
}

# vim:set sw=4 sts=4 et:
