# This is a -*- sh -*- library.

## I would use the builtin !, but that has the wrong semantics.
not () { "$@" && exit 1 || :; }

# trick: OS-detection (if needed)
abort_windows () {
if echo $OS | grep -i windows; then
  echo This test does not work on Windows
  exit 200
fi
}

pwd() {
    ghc --make -o hspwd "$TESTBIN/hspwd.hs" > /dev/null
    "./hspwd"
}

which() {
    type -P "$@" | cut -d' ' -f 3-
}

# switch locale to one supporting the latin-9 (ISO 8859-15) character set if possible, otherwise skip test

no_latin9_locale_warning () {
    echo "no ISO 8859-15 locale found, skipping test"
    echo "try (eg): sudo locale-gen en_US.ISO-8859-15"
}

switch_to_latin9_locale () {
    if echo $OS | grep -i windows; then
        chcp.com 28605
    else
        if ! which locale ; then
            echo "no locale command, skipping test"
            exit 200
        fi

        # look for a ISO 8859-15 locale. locale -a shows iso885915, on ubuntu at least
        latin9_locale=`locale -a | egrep --text -i iso8859-?15 | head -n 1` || (no_latin9_locale_warning; exit 200)
        test -n "$latin9_locale" || (no_latin9_locale_warning; exit 200)

        echo "Using locale $latin9_locale"
        export LC_ALL=$latin9_locale
        echo "character encoding is now `locale charmap`"
    fi
}

# switch locale to utf8 if supported if there's a locale command, skip test
# otherwise
switch_to_utf8_locale () {
    if echo $OS | grep -i windows; then
        chcp.com 65001
    else
        if ! which locale ; then
            echo "no locale command"
            exit 200 # skip test
        fi

        utf8_locale=`locale -a | grep --text .utf8 | head -n 1` || exit 200
        test -n "$utf8_locale" || exit 200

        echo "Using locale $utf8_locale"
        export LC_ALL=$utf8_locale
        echo "character encoding is now `locale charmap`"
    fi
}

serve_http() {
    cat > light.conf <<EOF
    server.document-root       = "$PWD"
    server.errorlog            = "/dev/null"
    server.port                = 23032 ## FIXME
    server.bind                = "localhost"
    server.pid-file            = "$PWD/light.pid"
EOF
    trap "finish_http \"$PWD\"" EXIT
    lighttpd -f light.conf || exit 200
    ps `cat light.pid` > /dev/null 2>&1 || exit 200
    baseurl="http://localhost:23032"
}

finish_http() {
    test -e "$1/light.pid" && kill `cat "$1/light.pid"` || true
}

check_remote_http() {
  if ! curl -fI "$1"; then
    echo Cannot reach "$1"
    exit 200
  fi
}

skip-formats() {
    for f in "$@"; do grep $f $HOME/.darcs/defaults && exit 200 || true; done
}

# check that the specified string appears precisely once in the output
grep-once() {
    grep -c "$@" | grep -w 1
}

require_ghc() {
    test $GHC_VERSION -ge $1 || exit 200
}

grep -q darcs-2 .darcs/defaults && format=darcs-2
grep -q darcs-1 .darcs/defaults && format=darcs-1

set -vex -o pipefail