#!/usr/bin/perl
use strict;
use warnings;

#Converts Fastaq python scripts usage into man pages.
#The man pages are placed in the man folder of the main Fastaq directory

createManPages();

sub createManPages {

  my $source= 'scripts';
  my $destination= 'debian/man';
  my $app_name = 'Fastaq';


  unless ( -d $destination ) {
    system(mkdir $destination);
  }

  my @files;

  push(@files,`ls $source/fastaq_*`);

  if ( scalar @files > 0 ) {

    print "Creating manpages\n";
    for my $file ( @files ) {
      $file =~ s/\n$//;

      my $filename = $file;
      $filename =~ s/$source\///;

      my $uc_filename = uc($filename);
      my $man_file = $filename;

      $man_file = $destination . '/' . $man_file . '.1';

      open (my $man_fh, ">", $man_file);

      my $grep_string = $filename . ': error: too few arguments';

      my $cmd = "help2man -m $filename -n $filename --no-discard-stderr $file | sed 's/usage://gi'";
      my @output;
      push(@output, `$cmd`);

      for my $line (@output) {
	$line =~ s/\n$//;

      }

      for (my $i = 0; $i < scalar @output; $i++) {
	my $output_line = $output[$i];

	if ($output_line =~ m/^\.TH/) {
	  $output_line =~ s/\s+/ /g;
	  $output_line =~ s/(\.TH) ("\d+") ("[a-zA-Z0-9_ ]*") ("[a-zA-Z0-9_<>\[\]\/\.\(\), ]*") ("[a-zA-Z0-9_]*")/$1 $uc_filename $2 $3 "$app_name" "Fastaq executables"/;
	}

	$output_line =~ s/ \\- $filename/$filename/;

	if ( $output_line =~ m/^.PP/ && $output[$i + 1] =~ m/^$filename\:/ ) {
	  $output_line = $output[$i + 1] = '';
	}

	if ($output_line =~ m/^\.SH "SEE ALSO"/) {
	  last;
	}
	print $man_fh "$output_line\n";
      }

      writeAuthorAndCopyright($man_fh,$filename);
      close($man_fh);
    }
    print "Manpage creation complete\n";
  }
}

sub writeAuthorAndCopyright {

  my ($man_fh,$filename) = @_;

  my $author_blurb = <<END_OF_AUTHOR_BLURB;
.SH "AUTHOR"
.sp
$filename was originally written by Martin Hunt (mh12\@sanger.ac.uk)
END_OF_AUTHOR_BLURB

  print $man_fh "$author_blurb\n";

  my $copyright_blurb = <<'END_OF_C_BLURB';
.SH "COPYING"
.sp
Wellcome Trust Sanger Institute Copyright \(co 2013 Wellcome Trust Sanger Institute This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version\&.
END_OF_C_BLURB

  print $man_fh "$copyright_blurb\n";

}
