// ============================================================= //
//                                                               //
//   File      : arb_sub2ascii.cxx                               //
//   Purpose   : unittest support tool                           //
//                                                               //
//   Coded by Ralf Westram (coder@reallysoft.de) in April 2018   //
//   http://www.arb-home.de/                                     //
//                                                               //
// ============================================================= //

#include <arbdbt.h>

static int fail_if_error(const char *error) {
    if (error) {
        fprintf(stderr, "arb_sub2ascii: Error: %s\n", error);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

static int show_usage(const char *error) {
    fputs("arb_sub2ascii - extract part of database into ascii database\n"
          "(intended to support fine-grained results in unit-tests)\n"
          "Syntax: arb_sub2ascii 'srcDB' 'path/to/container' 'dstDB'\n"
          "Opens arb-database 'srcDB', searches a container using the specified\n"
          "search path and dumps its contents in arb ascii format to 'dstDB'\n",
          stderr);

    return fail_if_error(error);
}

int ARB_main(int argc, char *argv[]) {
    GB_ERROR error = NULp;

    bool not_enough_args = argc<4;
    bool help_requested  = argc>1 && strcmp(argv[1], "--help") == 0;

    if (not_enough_args || help_requested) {
        return show_usage(help_requested ? NULp : "not enough arguments");
    }

    const char *srcname = argv[1];
    const char *path    = argv[2];
    const char *dstname = argv[3];

    {
        GB_shell shell;

        GBDATA *gb_src = GB_open(srcname, "r");
        GBDATA *gb_dst = NULp;

        if (!gb_src) error = GB_await_error();
        else {
            gb_dst             = GB_open(dstname, "cw");
            if (!gb_dst) error = GB_await_error();
        }

        if (!error) {
            GB_transaction ts(gb_src);
            GB_transaction td(gb_dst);

            GBDATA *gb_sub = GB_search(gb_src, path, GB_FIND);
            if (!gb_sub) {
                error = GBS_global_string("could not find a container at '%s' in database '%s'", path, srcname);
            }
            else {
                error = GB_copy_dropMarksAndTempstate(gb_dst, gb_sub);
            }
        }

        if (!error) error = GB_save_as(gb_dst, dstname, "a");

        if (gb_dst) GB_close(gb_dst);
        if (gb_src) GB_close(gb_src);
    }

    return fail_if_error(error);
}

