#! /usr/bin/perl

use warnings;
use strict;

sub optionstonroff
  {
    my $options = shift;
    my $ret = "";
    foreach( split /\n/, $options )
      {
	if( /^  (--?[[:alpha:]]+, )?(--[[:alpha:]-]*)( [<>[:alpha:]]*)? *(.*)$/ )
	  {
	    my $short;
	    my $long;
	    my $arg;
	    my $desc;
	    if( $1 ) { $short = $1; } else { $short = ""; };
	    if( $2 ) { $long = $2; } else { $long = ""; };
	    if( $3 ) { $arg = $3; } else { $arg = ""; };
	    if( $4 ) { $desc = $4; } else { $desc = ""; };
	    $ret .= ".TP\n";
	    $ret .= ".B $short $long $arg\n";
	    $ret .= "$desc\n";
	  }
	elsif( /^  ([[:alpha:]]+) +(.*)$/ )
	  {
	    $ret .= ".TP\n";
	    $ret .= ".B $1\n";
	    $ret .= "$2\n";
	  }
	elsif( /^ +(.*)$/ )
	  {
	    $ret .= "$1\n";
	  }
	elsif( ! /^$/ )
	  {
	    # this means a header like "Qt Options:" I'm wondering
	    # what to do with this, I don't know enough nroff to
	    # format it nicely, I'm affraid..
	  }
      }
    return $ret;
  };

sub usage
  {
    print "USAGE: $0 app\n";
  };

if( $#ARGV < 0 ){
  usage();
  exit 1;
}

my $runapp = $ARGV[0];
if ( ! -x $runapp )
  {
    print "Error: $runapp is not executable.\n";
    exit 1;
  };

my $shortdescription = `$runapp --help | sed -ne '3p'`;
chomp $shortdescription;

my $synopsis = `$runapp --help | sed -n '1p' | sed -e 's/[^:]*: //'`;
chomp $synopsis;
my $appname = $synopsis;
$appname =~ s/ .*$//;
my $ucappname = uc $appname;

my $options = `$runapp --help-all | sed -e '1,4d'`;
$options = optionstonroff( $options );

my $timespec = ucfirst `date '+%b %G'`;
chomp $timespec;

my $description = $shortdescription;
if( -r "control" )
  {
    $description = `cat control | sed -ne '/Package: $appname\$/,/^\$/p' | egrep -v '^\\w*:.*\$' | sed -e 's/^ //' | sed -e 's/^\\.//'`;
# leads to problems in some cases :(
#    $description =~ s/KDE ?/\n.SM KDE\n/g;
  }

my $authors = `$runapp --author | sed -ne '2,\$p' | sed -e '\$d' | sed -e 's/^ *//'`;
$authors =~ s/\n/\n.br\n/g;

print <<EOF;
.\\\" DO NOT MODIFY THIS FILE!  It was generated by kdemangen.pl 0.1
.TH $ucappname 1 \"$timespec\" \"K Desktop Environment\" \"$shortdescription\"
.SH NAME
$appname
\- $shortdescription
.SH SYNOPSIS
$synopsis
.SH DESCRIPTION
$description
.SH OPTIONS
$options
.SH SEE ALSO
.BR help:/$appname
\- The $appname documentation.
.br
.SH AUTHORS
.nf
$authors
EOF
