#!/usr/bin/env perl
package main;
use strict;
use warnings;

our $VERSION = '0.001006'; # TRIAL

my ($dir, %args) = @ARGV;

if ($args{setsid}) {
    require POSIX;
    POSIX::setsid();
}

my $pid = $$;
END {
    local ($?, $!, $@);
    if ($args{pfile} && -f $args{pfile} && $pid == $$) {
        print "Deleting $args{pfile}\n";
        unlink($args{pfile}) or warn "Could not delete $args{pfile}: $!\n";
    }
}

require Test2::Harness::Run::Runner;
my $spawn = Test2::Harness::Run::Runner->new(
    dir => $dir,
);

my $test_file = $spawn->start;

# Do not keep these signal handlers post-fork when we are running a test file.
$SIG{HUP}  = 'DEFAULT';
$SIG{INT}  = 'DEFAULT';
$SIG{TERM} = 'DEFAULT';

unless($test_file) {
    my $complete = File::Spec->catfile($dir, 'complete');
    open(my $fh, '>', $complete) or die "Could not open '$complete'";
    print $fh '1';
    close($fh);
    exit 0;
}

$@ = '';
do $test_file;
die $@ if $@;

exit 0;

__END__

=pod

=encoding UTF-8

=head1 NAME

yath-spawn - Script used when spawning a test run process.

=head1 DESCRIPTION

=head1 SOURCE

The source code repository for Test2-Harness can be found at
F<http://github.com/Test-More/Test2-Harness/>.

=head1 MAINTAINERS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 AUTHORS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 COPYRIGHT

Copyright 2017 Chad Granum E<lt>exodist7@gmail.comE<gt>.

This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

See F<http://dev.perl.org/licenses/>

=cut
