/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2023 Brett Sheffield <bacs@librecast.net> */

#define _DEFAULT_SOURCE   /* be64toh */
#define _XOPEN_SOURCE 700 /* for nftw() */
#include "test.h"
#include "testdata.h"
#include "testsync.h"
#include <sys/types.h>
#include <errno.h>
#include <dirent.h>
#include <ftw.h>
#include <librecast_pvt.h>
#include <librecast/mdex.h>
#include <librecast/mtree.h>
#include <librecast/sync.h>
#include <unistd.h>

#define MAXFILESZ 1048576
#define MAXFILES 10
#define MAXDIRS 5
#define DEPTH 2

/*
 * test 0114
 *
 * create a tree of files and directories and use lc_syncfilelocal() to sync
 * recursively to destination directory.
 *
 * Compare the resulting directories and ensure they match.
 */

int main(int argc, char *argv[])
{
	(void)argc;
	char *src = NULL, *dst = NULL;
	const int flags =
		SYNC_RECURSE | SYNC_ATIME | SYNC_MTIME | SYNC_OWNER | SYNC_GROUP | SYNC_MODE;
	int rc;

	test_name("lc_syncfilelocal() - recursive file syncing");

	/* create source directory tree and files */
	rc = test_createtestdirs(basename(argv[0]), &src, &dst);
	if (!test_assert(rc == 0, "test_createtestdirs()")) return test_status;
	rc = test_createtesttree(src, MAXFILESZ, MAXFILES, MAXDIRS, DEPTH, 0);
	if (!test_assert(rc == 0, "test_createtesttree()")) goto err_free_src_dst;

#if 0
	/* XXX; match src and dst match */
	char cmd[128];
	//snprintf(cmd, sizeof cmd, "rsync -avq %s/ %s", src, dst);
	snprintf(cmd, sizeof cmd, "cp -Rp %s/. %s", src, dst);
	test_log("`%s`\n", cmd);
	if (system(cmd)) { test_assert(0, "cmd failed"); goto err_free_src_dst; }
#endif

	/* sync dst from src */
	rc = lc_syncfilelocal(dst, src, NULL, NULL, NULL, flags);
	if (!test_assert(rc == 0, "lc_syncfilelocal() returned %i", rc)) goto err_free_src_dst;

	/* verify src and dst match */
	test_verify_dirs(src, dst);
err_free_src_dst:
	free(src); free(dst);
	return test_status;
}
