#!/bin/sh
set -e
cd "$AUTOPKGTEST_TMP"

cat > api_test.c << 'EOF'
#include <bstrlib.h>
#include <stdio.h>
#include <stdlib.h>

#define CHECK(cond, msg) \
    do { if (!(cond)) { fprintf(stderr, "FAIL: %s\n", msg); exit(1); } } while(0)

int main(void) {
    /* creation and length */
    bstring b = bfromcstr("hello");
    CHECK(b != NULL, "bfromcstr returned NULL");
    CHECK(blength(b) == 5, "length of 'hello' should be 5");

    /* concatenation */
    CHECK(bcatcstr(b, " world") == BSTR_OK, "bcatcstr failed");
    CHECK(blength(b) == 11, "length after concat should be 11");
    CHECK(biseqcstr(b, "hello world") == 1, "biseqcstr mismatch after concat");

    /* copy */
    bstring copy = bstrcpy(b);
    CHECK(copy != NULL, "bstrcpy returned NULL");
    CHECK(biseq(b, copy) == 1, "copy should equal original");

    /* substring */
    bstring sub = bmidstr(b, 6, 5);
    CHECK(sub != NULL, "bmidstr returned NULL");
    CHECK(biseqcstr(sub, "world") == 1, "substring should be 'world'");

    /* split */
    bstring sentence = bfromcstr("one,two,three");
    struct bstrList *parts = bsplit(sentence, ',');
    CHECK(parts != NULL, "bsplit returned NULL");
    CHECK(parts->qty == 3, "bsplit should produce 3 parts");
    CHECK(biseqcstr(parts->entry[0], "one") == 1, "part[0] should be 'one'");
    CHECK(biseqcstr(parts->entry[2], "three") == 1, "part[2] should be 'three'");

    /* case conversion */
    bstring upper = bstrcpy(b);
    CHECK(btoupper(upper) == BSTR_OK, "btoupper failed");
    CHECK(biseqcstr(upper, "HELLO WORLD") == 1, "uppercase mismatch");

    /* find/replace */
    bstring haystack = bfromcstr("aabbaabb");
    bstring needle   = bfromcstr("aa");
    bstring repl     = bfromcstr("x");
    CHECK(bfindreplace(haystack, needle, repl, 0) == BSTR_OK, "bfindreplace failed");
    CHECK(biseqcstr(haystack, "xbbxbb") == 1, "bfindreplace result mismatch");

    /* search */
    bstring hay2 = bfromcstr("foobar");
    bstring needle2 = bfromcstr("bar");
    CHECK(binstr(hay2, 0, needle2) == 3, "binstr should find 'bar' at pos 3");

    bdestroy(b);
    bdestroy(copy);
    bdestroy(sub);
    bdestroy(sentence);
    bdestroy(upper);
    bdestroy(haystack);
    bdestroy(needle);
    bdestroy(repl);
    bdestroy(hay2);
    bdestroy(needle2);
    bstrListDestroy(parts);

    puts("api PASS");
    return 0;
}
EOF

gcc -o api_test api_test.c $(pkg-config --cflags --libs bstring)
./api_test
echo "bstring api test PASS"

