# -*- Autotest -*-

AT_BANNER([xorg utils lib])

AT_TESTCFUN([xorg_utils_skip_pfx],
        [$XORG_UTILS_CFLAGS],
        [$XORG_UTILS_LDFLAGS],
[[
#include "libabrt.h"
#include "xorg-utils.h"

int main(void)
{
    const char *str[] = {
        "[xxx xxx] (EE) Foo",
        " (EE) Foo",
        "(EE) Foo",
        " Foo",
        "Foo",
        NULL
    };

    for (int i = 0; str[i] != NULL; ++i)
    {
        char *result = skip_pfx((char *)str[i]);
        if (strcmp(result, "Foo") != 0)
        {
            printf("Error: expected: 'Foo' got: '%s'\n", result);
            return 1;
        }
    }

    return 0;
}
]])

AT_TESTCFUN([xorg_crash_info_save_in_dump_dir],
        [$XORG_UTILS_CFLAGS],
        [$XORG_UTILS_LDFLAGS],
[[
#include "libabrt.h"
#include "xorg-utils.h"

void test(const char *backtrace, const char *exp_backtrace,
          const char *reason, const char *exp_reason,
          const char *exe, const char *exp_exe)
{
    char template[] = "/tmp/XXXXXX/dump_dir";

    char *last_slash = strrchr(template, '/');
    *last_slash = '\0';

    if (mkdtemp(template) == NULL) {
        perror("mkdtemp()");
        return EXIT_FAILURE;
    }

    *last_slash = '/';

    struct dump_dir *dd = dd_create(template, (uid_t)-1, 0640);

    dd_create_basic_files(dd, (uid_t)-1, NULL);

    struct xorg_crash_info *crash_info = xmalloc(sizeof(struct xorg_crash_info));
    crash_info->backtrace = xstrdup(backtrace);
    crash_info->reason = xstrdup(reason);
    crash_info->exe = xstrdup(exe);

    xorg_crash_info_save_in_dump_dir(crash_info, dd);

    dd_close(dd);
    dd = NULL;

    dd = dd_opendir(template, 0);
    assert(dd != NULL);
    assert(strcmp(dd->dd_dirname, template) == 0);

    problem_data_t *pd = create_problem_data_from_dump_dir(dd);

    assert(strcmp(problem_data_get_content_or_NULL(pd, FILENAME_ANALYZER), "abrt-xorg") == 0);
    assert(strcmp(problem_data_get_content_or_NULL(pd, FILENAME_TYPE), "xorg") == 0);
    assert(strcmp(problem_data_get_content_or_NULL(pd, FILENAME_REASON), exp_reason) == 0);
    assert(strcmp(problem_data_get_content_or_NULL(pd, FILENAME_BACKTRACE), exp_backtrace) == 0);
    assert(strncmp(problem_data_get_content_or_NULL(pd, FILENAME_EXECUTABLE), exp_exe, strlen(exp_exe)) == 0);

    problem_data_free(pd);
    xorg_crash_info_free(crash_info);

    dd_delete(dd);

    struct stat dd_st;
    assert(stat(template, &dd_st) != 0);

    *last_slash = '\0';
    assert(rmdir(template) == 0);
}

int main(void)
{
    g_verbose = 3;

    const char *b = "I am a backtrace";
    const char *r = "Reason here!";
    const char *e = "Executable here!";

    test(b, b, r, r, e, e);
    test(b, b, r, r, NULL, "/usr/bin/X");

    return EXIT_SUCCESS;
}
]])

