package Hurd::Trans::Hello;

use Hurd::Trivfs;
@ISA = ('Hurd::Trivfs');

use strict;

my (%opt);
%opt = (
	text => "Hello, world!\n",
       );

use Getopt::Long;
GetOptions (\%opt,
	    'help+', 'version+',
	    'text=s', 'quiet+'
	   );

if ($opt{help}) {
    print "
Usage: settrans -c FILE /usr/bin/perl -M".__PACKAGE__." -e0 [-- OPTIONS]

    --text    STRING      Specify the file contents.
";
    exit 0;

} elsif ($opt{version}) {
    { no strict; print __PACKAGE__."$VERSION\n"; }
    exit 0;
}

my ($text, $text_len);
$text = $opt{text};
$text_len = length $text;

warn "Hello Perl translator pid $$ started\n"
    unless $opt{quiet};
__PACKAGE__->start;
warn "Hello Perl translator pid $$ exiting due to boredom\n"
    unless $opt{quiet};
exit;


# Now the fun begins...

$support_write = 0;

sub goaway {
    warn "Hello Perl translator pid $$ exiting on goaway request\n"
	unless $opt{quiet};
    exit;
}

sub init_peropen {
    my ($self, $po) = @_;

    # The hook can hold any scalar value.
    # I'm using it to store the current offset.
    $po->hook (0);
}

sub io_read {
    my ($self, $prot, $bufref, $offset, $amount) = @_;

    if ($offset == -1) {
	$offset = $prot->po->hook;
    }
    $$bufref = substr ($text, $offset, $amount);
    $prot->po->hook ($offset + length $$bufref);
}

sub io_seek {
    my ($self, $prot, $offset, $whence);
    my ($offs);

    $offs = $prot->po->hook;

    # XXX assumes SEEK_CUR == 0 etc.
    if ($whence == 0) {
	$offs = $offset;
    } elsif ($whence == 1) {
	$offs += $offset;
    } elsif ($whence == 2) {
	$offs = $text_len - $offset;
    } else {
	$! = Errno::EINVAL;
	return undef;
    }
    $prot->po->hook ($offs);
    return $offs;
}

1;
__END__

=head1 NAME

Hurd::Trans::Hello - simple example translator in Perl

=head1 SYNOPSIS

  settrans -ac hello /bin/perl -MHurd::Trans::Hello -e0
  cat hello

=head1 DESCRIPTION

This module allows you to use /bin/perl as a simple file translator.
Run `perl -MHurd::Trans::Hello -e0 -- --help' for a usage message.

=head1 AUTHOR

John Tobey, jtobey@john-edwin-tobey.org

=head1 SEE ALSO

perl(1).

=cut
