/* This code is PUBLIC DOMAIN, and is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. See the accompanying 
 * LICENSE file.
 */
#include "apr.h"
#include "apr_file_io.h"
#include "apr_file_info.h"
#include <stdlib.h>

static apr_status_t ls(const char *path, apr_file_t *out, apr_pool_t *pool)
{
    apr_status_t rv;
    apr_dir_t *d;

    rv = apr_dir_open(&d, path, pool);
    if (rv)
        return rv;

    for (;;) {
        apr_finfo_t fi;

        rv = apr_dir_read(&fi, APR_FINFO_NAME | APR_FINFO_TYPE, d);
        if (APR_STATUS_IS_ENOENT(rv))
            break;
        else if (rv)
            return rv;

        if ((fi.name[0] == '.' && fi.name[1] == '\0')
            || (fi.name[0] == '.' && fi.name[1] == '.' && fi.name[2] == '\0'))
            continue;

        apr_file_printf(out, "%s%s" APR_EOL_STR, fi.name,
                        fi.filetype == APR_DIR ? "/" : "");
    }

    return APR_SUCCESS;
}

int main(int argc, const char * const argv[])
{
    apr_pool_t *pool, *subpool;
    apr_file_t *out;
    apr_status_t rv;
    int i;

    apr_initialize();
    atexit(apr_terminate);
    apr_pool_create(&pool, NULL);
    
    apr_file_open_stdout(&out, pool);

    apr_pool_create(&subpool, pool);

    for (i = 1; i < argc; ++i) {
        apr_pool_clear(subpool);

        rv = ls(argv[i], out, subpool);
        if (rv)
            return EXIT_FAILURE;
    }

    apr_pool_destroy(subpool);

    return EXIT_SUCCESS;
}
