/* main.c */

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include "vm.h"
#include "plugins.h"

/* This macro exists purely to shorten subsequent lines for readability */
#define PT(i) plugins_table[i]

void finish(void)
{
	int i;

	for (i = nplugins-1; i >= 0; i--) {
		printf("Shutting down plugin '%s'\n", PT(i).pl_name);
		(PT(i).pl_init)();
		printf("Plugin '%s' shut down\n", PT(i).pl_name);
		PT(i).pl_active = 0;
	}

	exit(0);
}

void sigint_handler(int signal)
{
	finish();
}

int main(int argc, char *argv[])
{
	int i;

	argv++;
	argc--;
	if (argc != 1)
		errx(1, "Usage: lsi <filename>");
	vm_init();
	vm_load(argv[0]);
	signal(SIGINT, sigint_handler);

	/* Initialise plugins */
	for (i = 0; i < nplugins; i++) {
		printf("Initialising plugin '%s'\n", PT(i).pl_name);
		if ((PT(i).pl_init)()) {
			printf("Plugin '%s' initialised\n", PT(i).pl_name);
			PT(i).pl_active = 1;
		} else {
			printf("Plugin '%s' failed\n", PT(i).pl_name);
			PT(i).pl_active = 0;
		}
	}

	/* Showtime */
	vm_spawn("main");
	vm_run();
	finish();
	return 0;
}
