#!/bin/sh
# Use of any --include or --exclude* option would segfault in 2.6 and 2.6.1
. "${srcdir=.}/init.sh"; path_prepend_ ../src

mkdir -p x/dir || framework_failure_
echo aaa > x/a || framework_failure_
echo bbb > x/b || framework_failure_
echo ddd > x/dir/d || framework_failure_

printf '%s\n' x/b:bbb x/dir/d:ddd > exp-not-a   || framework_failure_
printf '%s\n'         x/dir/d:ddd > exp-not-ab  || framework_failure_
printf '%s\n' x/a:aaa x/b:bbb     > exp-not-d   || framework_failure_
printf '%s\n' x/a:aaa x/b:bbb     > exp-not-dir || framework_failure_
printf '%s\n' x/a:aaa             > exp-a       || framework_failure_
printf '%s\n' a:aaa               > exp-aa      || framework_failure_
printf '%s\n' aaa                 > exp-aaa     || framework_failure_
printf '%s\n' ./x/a ./x/b ./x/dir/d | sort > exp-dotnames || framework_failure_

grep -r --exclude='a*'    . x > out || fail=1
sort out > k && mv k out
compare exp-not-a out || fail=1

grep -r --exclude='Rumpelstiltskin' --include='a*' --exclude='a*' . x > out ||
  fail=1
sort out > k && mv k out
compare exp-not-a out || fail=1

grep -r --exclude='[ab]'  . x > out || fail=1
sort out > k && mv k out
compare exp-not-ab out || fail=1

grep -r --exclude='*d'    . x > out || fail=1
sort out > k && mv k out
compare exp-not-d out || fail=1

grep -r --exclude-dir=dir . x > out || fail=1
sort out > k && mv k out
compare exp-not-dir out || fail=1

grep -r --exclude-dir=dir/ . x > out || fail=1
sort out > k && mv k out
compare exp-not-dir out || fail=1

# Test with a non-glob.
grep -r --include=a    . x > out || fail=1
# no need to sort
compare exp-a out || fail=1

# Also test --include with a "glob".
grep -r --include='a*'    . x > out || fail=1
# no need to sort
compare exp-a out || fail=1

# --include (without --recursive) uses different code
grep --directories=skip --include=x/a --exclude-dir=dir '^aaa$' x/* > out \
    || fail=1
compare exp-a out || fail=1

(cd x && grep -r --exclude-dir=. '^aaa$') > out || fail=1
compare exp-aa out || fail=1

grep --exclude=- '^aaa$' - < x/a > out || fail=1
compare exp-aaa out || fail=1

for exclude in 'x' 'x*'; do
    grep -rl --exclude-dir="$exclude" . x > out
    test $? -eq 1 || fail=1
    compare /dev/null out || fail=1
done

for exclude in 'x' 'x*' './x' './x*'; do
    grep -rl --exclude-dir="$exclude" . ./x | sort > out || fail=1
    compare /dev/null out || fail=1
done

Exit $fail
