use strict;
use warnings;

use Test::More;

use File::Temp qw/tempdir/;
use IO::Socket::UNIX;

my $ok = ok(
    eval { defined PF_UNIX and socket(my $tmp, PF_UNIX, SOCK_STREAM, 0); 1 },
    "UNIX Sockets appear to be supported"
);

diag "UNIX check: $ok | $^O";
diag "UNIX check: $ok | $^O";
diag "UNIX check: $ok | $^O";

my $dir = tempdir();

my $file = "$dir/$$.socket";

my $listen = IO::Socket::UNIX->new(
    Listen => 1,
    Local  => "$file",
) || die "Could not open socket!";

# Server
if (my $pid = fork) {
    local $SIG{ALRM} = sub { ok(0, "Got Message"); diag "Timeout!"; die };

    eval {
        alarm 5;
        my $client = $listen->accept;
        chomp(my $got = <$client>);
        is($got, 'Hello!', "Got message");
        alarm 0;
    };

    waitpid($pid, 0);
    done_testing;
    exit 0
}
else {
    close($listen);

    my $socket = IO::Socket::UNIX->new(Peer => "$file") || die "Could not connect!";
    print $socket "Hello!\n";

    exit 0;
}
