#!/usr/bin/perl

# 23:17:32 < ingy> so Kwiki-Foo-Bar/lib/Kwiki/Foo/Bar.pm => 
#                  Kwiki-Foo-Bar/src/doc/Kwiki/Foo/Bar.pod
#

use strict;
use warnings;
use lib 'lib';
use IO::All;
use File::Basename;
use Shell 'mkdir';

my $list = io( "ack -l '^=\\w+' @ARGV|" ) or die $!;

while (my $file = $list->chomp->readline) {
    print "$file \n";

    my $dest = $file;
    $dest =~ s|lib|src/doc|;
    $dest =~ s/\.\w+$/.pod/;
    next if -e $dest;

    print "\t=> $dest\n";

    # my $bak = $file.".bak";
    my $bak = "bak";
    io($bak) < io($file);

    mkdir(-p => dirname($dest));
    my $pod  = io $dest or die $!;
    my $code = io $file or die $!;
    my $src  = io $bak or die $!;

    my $c = '';
    my $p = '';

    my $in_pod = 0;
    while (my $l = $src->readline) {
	if ($l =~ /^=\w/ and not $l =~ /^=cut/) {
	    $in_pod = 1;
	}

	if($in_pod) {
            $p .= $l;
	} else {
            $c .= $l;
	}

	if ($l =~ /^=cut/ or $l =~ /^__\w+/)  {
	    $in_pod = 0;
	}
    }
    $p =~ s/^=cut\s+\z//m;
    $c =~ s/^__DATA__\s+\z//m;
    $c =~ s/^__END__\s+\z//m;
    $p =~ s/\s+\z/\n/;
    $c =~ s/\s+\z/\n/;
    $pod->print($p);
    $code->print($c);

    $_->close for ($pod, $src, $code);
    unlink($bak);
}

__END__

=head1 NAME

rippod - extract pod from a directory full of perl

=head1 SYNOPSIS

rippod sourcedir ...

=head1 DESCRIPTION

remove pod from all the perl found in lib  and place it in src/doc in the target
directory.
  
=head1 BUGS

Probably, let me know if you find them

=head1 SEE ALSO

other things that make your life interesting

=head1 AUTHOR

(c) 2007
Chris Fedde <cfedde at cpan.org>
Ingy döt Net <ing at cpan.org 

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