#include <EXTERN.h>
#include <perl.h>
#include "perlxsi.h"

PerlInterpreter *my_perl;

int main(int argc, char *argv[])
{
	fprintf(stderr, "Perl scripting host starting up\n");

	int commfd = atoi(argv[--argc]);
	if (fcntl(commfd, F_GETFL) == -1) {
		fprintf(stderr, "ERROR: Perl scripting couldn't establish comm: %m");
		exit(EXIT_FAILURE);
	}

	PERL_SYS_INIT3(&argc, &argv, NULL);
	my_perl = perl_alloc();
	perl_construct(my_perl);

	perl_parse(my_perl, xs_init, argc, argv, NULL);
	//PL_exit_flags |= PERL_EXIT_DESTRUCT_END;

	SV *commsv = get_sv("VDR::_comm_fileno", TRUE);
	sv_setiv(commsv, commfd);

	perl_run(my_perl);

	FILE *comm = fdopen(commfd, "r+");
	fprintf(comm, "Q\n");
	fclose(comm);

	perl_destruct(my_perl);
	perl_free(my_perl);
	PERL_SYS_TERM();
	
	fprintf(stderr, "Perl scripting host shutting down\n");

	return EXIT_SUCCESS;
}
