#!/usr/pkg/bin/perl

# PODNAME: ebug_client
# ABSTRACT: Debugger server for remote debugging Perl script
our $VERSION = '0.64'; # VERSION


#use lib::findbin '../lib'; # dev-only
use String::Koremutake;
use Getopt::Long;
use strict;
use warnings;

GetOptions( my $OPT = {}, 'help', 'port=i', 'keepio' ) || help();
help() if $OPT->{help} || !@ARGV;
help() if $OPT->{port} && $OPT->{port} < 3141;

my $cmd  = "$^X -d:ebug::Backend @ARGV";
my $gen  = String::Koremutake->new;
my $rand = $OPT->{port} ? $OPT->{port} - 3141 : int( rand(100_000) );
my $key  = $gen->integer_to_koremutake($rand);
my $port = 3141 + ( $rand % 1024 );

$ENV{PERL_DEBUG_DONT_RELAY_IO} = 1 if $OPT->{keepio};
$ENV{SECRET} = $key;

print STDERR <<EOF;
Debuggee started. Please attach with:

 ebug_client -key $key -port $port

Waiting...
EOF
exec($cmd);

exit(0);

sub help {
    print STDERR <<EOF;
Usage: $0 [-help][-port <n>] -- debuggee args...
Note:
- Listening port must be >= 3141
EOF
    exit(1);
}

__END__

=pod

=encoding UTF-8

=head1 NAME

ebug_client - Debugger server for remote debugging Perl script

=head1 VERSION

version 0.64

=head1 SYNOPSIS

 ebug_server [-keepio][-port port] -- script args...

=head1 DESCRIPTION

L<ebug_server> is an debugger server for remote debugging
Perl script, using L<ebug_client>.

When invoked, it will show you how to invoke L<ebug_client>.

=head1 EXAMPLE

 # Run hello.pl and wait for "ebug_client" to attach
 $ ebug_server -- hello.pl
 
 # Same as above, but keep I/O happen on server side
 $ ebug_server -keepio -- hello.pl

=head1 NOTE

You can't specify secret key - it must be generated automatically.
Also, you can't specify port below 3141.

Since Devel::ebug::Backend listens to "localhost" socket,
you will need to relay I/O using tool like socat for true
remote debugging.

=head1 SEE ALSO

L<Devel::debug>, L<ebug>, L<ebug_client>

=head1 AUTHOR

Original author: Leon Brocard E<lt>acme@astray.comE<gt>

Current maintainer: Graham Ollis E<lt>plicease@cpan.orgE<gt>

Contributors:

Brock Wilcox E<lt>awwaiid@thelackthereof.orgE<gt>

Taisuke Yamada

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2005-2021 by Leon Brocard.

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

=cut
