/*
 *                            COPYRIGHT
 *
 *  cschem - modular/flexible schematics editor - libcschem (core library)
 *  Copyright (C) 2019,2020 Tibor 'Igor2' Palinkas
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.*
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */

#include <librnd/core/compat_inc.h>
#include "config.h"
#include <librnd/core/misc_util.h>

#include <librnd/core/compat_misc.h>
#include <librnd/core/compat_fs.h>
#include <librnd/core/error.h>
#include <librnd/core/paths.h>
#include <librnd/core/safe_fs.h>
#include <librnd/core/safe_fs_dir.h>
#include <librnd/core/globalconst.h>
#include <librnd/core/compat_lrealpath.h>

#include "util_lib_fs.h"


char *csch_lib_fs_realpath(rnd_design_t *hl, const char *root)
{
	char *patha, *rp;
	const char *path = root;

	if (*path == '?')
		path++;

	patha = rnd_build_fn(hl, path);
	rp = rnd_lrealpath(patha);
	free(patha);
	return rp;
}

void csch_lib_fs_map(rnd_design_t *hl, csch_lib_backend_t *be, csch_lib_t *parent, gds_t *path, csch_lib_type_t (*type_cb)(rnd_design_t *, const char *fn))
{
	DIR *dir;
	struct dirent *de;
	long save = path->used, restore;
	csch_lib_t *newent;
	
	dir = rnd_opendir(hl, path->array);
	if (dir == NULL)
		return;

	gds_append(path, '/');
	restore = path->used;

	while((de = rnd_readdir(dir)) != NULL) {
		if (*de->d_name == '.') continue;

		gds_append_str(path, de->d_name);

		if (rnd_is_dir(hl, path->array)) {
			newent = csch_lib_alloc_append(be, parent, rnd_strdup(de->d_name), CSCH_SLIB_DIR);
			csch_lib_fs_map(hl, be, newent, path, type_cb);
		}
		else {
			csch_lib_type_t type = type_cb(hl, path->array);
			if (type != CSCH_SLIB_invalid)
				newent = csch_lib_alloc_append(be, parent, rnd_strdup(de->d_name), type);
			else
				newent = NULL;
		}
		if (newent != NULL)
			newent->realpath = rnd_strdup(path->array);
		path->used = restore;
	}

	path->used = save;
	rnd_closedir(dir);
}
