/* This file is part of cfpeek
   Copyright (C) 2011-2021 Sergey Poznyakoff

   Cfpeek is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   Cfpeek 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with cfpeek.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "cfpeek.h"

struct script_tab {
	char *lang;
	char *suf;
	void (*init)(void);
	void (*run)(struct grecs_node *);
	void (*done)(void);
};

static struct script_tab script_tab[] = {
#ifdef GUILE_VERSION_NUMBER
	{ "scheme", "scm\0", guile_init, guile_apply, guile_done },
#endif
	{ NULL }
};

static struct script_tab *cur_script;

static struct script_tab *
script_find_by_lang(const char *lang)
{
	struct script_tab *p;
	for (p = script_tab; p->lang; p++)
		if (strcasecmp(p->lang, lang) == 0)
			return p;
	return NULL;
}

static struct script_tab *
script_find_by_suffix(const char *suf)
{
	struct script_tab *p;
	for (p = script_tab; p->lang; p++) {
		char *s;

		for (s = p->suf; *s; s += strlen (s) + 1)
			if (strcmp (s, suf) == 0)
				return p;
	}
	return NULL;
}

void
script_select(const char *lang)
{
	cur_script = script_find_by_lang(lang);
	if (!cur_script) {
		grecs_error(NULL, 0, "unsupported scripting language: %s",
			    lang);
		exit(EX_USAGE);
	}
}

void
script_init()
{
	if (!(script_file || script_expr))
		return;

	if (!cur_script) {
		if (script_file) {
			char *suf = strrchr(script_file, '.');
			if (suf)
				cur_script = script_find_by_suffix(suf + 1);
		}
		if (!cur_script)
			cur_script = script_tab;
		
		if (!cur_script->lang) {
			grecs_error(NULL, 0,
				    "scripting support not compiled in");
			exit(EX_USAGE);
		}
	}
	
	cur_script->init();
}

int
script_run(struct grecs_node *node)
{
	if (script_file || script_expr) {
		cur_script->run(node);
		return 0;
	}
	return 1;
}
	
void
script_done()
{
	if (cur_script)
		cur_script->done();
}
