/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2021 Tobias Kortkamp <tobik@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"

#include <sys/types.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "array.h"
#include "flow.h"
#include "io.h"
#include "map.h"
#include "mempool.h"
#include "mtree.h"
#include "peg.h"
#include "peg/mtree.h"
#include "queue.h"
#include "str.h"

struct MtreeState {
	struct Mempool *pool;
	struct Array *dirnames;
	struct Queue *path;
	enum MtreeType type;
	struct Map *keywords;
	struct PEGCapture *filename_capture;
	struct PEGCapture *keyword_capture;
};

struct MtreeFile {
	const char *path;
	struct Map *keywords;
};

// Prototypes
static char *get_path(struct Mempool *, struct Queue *);
static struct Map *copy_map(struct Mempool *, struct Map *);
static enum PEGCaptureFlag capture_machine(struct PEGCapture *, void *);

char *
get_path(struct Mempool *extpool, struct Queue *path)
{
	SCOPE_MEMPOOL(pool);
	struct Array *components = mempool_array(pool);
	QUEUE_FOREACH_SLICE(path, 1, -1, struct PEGCapture *, capture) {
		char *component = str_ndup(pool, capture->buf, capture->len);
		array_append(components, component);
	}
	return str_join(extpool, components, "/");
}

struct Map *
copy_map(struct Mempool *pool, struct Map *m)
{
	struct Map *newmap = mempool_map(pool, str_compare);
	MAP_FOREACH(m, void *, key, void *, val) {
		map_add(newmap, key, val);
	}
	return newmap;
}

enum PEGCaptureFlag
capture_machine(struct PEGCapture *capture, void *userdata)
{
	struct MtreeState *this = userdata;
	switch ((enum PEGMtreeCapture)capture->state) {
	case PEG_MTREE_ACCEPT:
		break;
	case PEG_MTREE_FILENAME:
		this->filename_capture = capture;
		break;
	case PEG_MTREE_FILENAME_ACCEPT:
		if (this->filename_capture->len == 1 &&
		    strncmp(this->filename_capture->buf, ".", this->filename_capture->len) == 0) {
			queue_truncate(this->path);
			queue_push(this->path, this->filename_capture);
		} else if (queue_len(this->path) == 0) {
			// First file spec must be .
			return PEG_CAPTURE_STOP;
		} else if (this->filename_capture->len == 2 &&
			   strncmp(this->filename_capture->buf, "..", this->filename_capture->len) == 0) {
			queue_dequeue(this->path);
		} else {
			switch (this->type) {
			case MTREE_TYPE_DIR: {
				queue_push(this->path, this->filename_capture);
				struct MtreeFile *f = mempool_alloc(this->pool, sizeof(struct MtreeFile));
				f->path = get_path(this->pool, this->path);
				f->keywords = copy_map(this->pool, this->keywords);
				array_append(this->dirnames, f);
				break;
			} default:
				break;
			}
		}
		this->filename_capture = NULL;
		break;
	case PEG_MTREE_KEYWORD:
		this->keyword_capture = capture;
		break;
	case PEG_MTREE_KEYWORD_VALUE: {
		char *key = str_ndup(this->pool, this->keyword_capture->buf, this->keyword_capture->len);
		if (key[this->keyword_capture->len] == '=') {
			key[this->keyword_capture->len - 1] = 0;
		}
		const char *value = str_ndup(this->pool, capture->buf, capture->len);
		if (map_contains(this->keywords, key)) {
			map_remove(this->keywords, key);
		}
		map_add(this->keywords, key, value);
		break;
	}
	}
	return PEG_CAPTURE_CONTINUE;
}

int
mtree_main(int argc, const char *argv[])
{
	SCOPE_MEMPOOL(pool);
	struct MtreeState state = {
		.type = MTREE_TYPE_DIR,
		.pool = pool,
		.path = mempool_queue(pool),
		.dirnames = mempool_array(pool),
		.keywords = mempool_map(pool, str_compare),
	};
	FILE *f = fopen(argv[1], "r");
	char *buf = slurp(f, pool);
	struct PEG *peg = peg_new(buf, strlen(buf));
	printf("%d\n", peg_match(peg, peg_mtree_decode, capture_machine, &state));
	ARRAY_FOREACH(state.dirnames, struct MtreeFile *, f) {
		printf("%s\t\t", f->path);
		MAP_FOREACH(f->keywords, const char *, key, const char *, val) {
			printf("%s=%s ", key, val);
		}
		printf("\n");
	}
	return 0;
}
