#!/usr/bin/perl -w

=head1 NAME

 mmake - generate a Java Makefile

=head1 SYNOPSIS

 mmake [ -d ]

=head1 DESCRIPTION

This program will generate a Makefile for all Java source files in the
current and in all subdirectories.  Use the I<-d> option to accept all
defaults.

Use the Makefile generated with mmake as follows:

To compile Java files just type make. It's also possible to run make
with one of the following targets: I<src, doc, clean, help, jar,
install and depend> Where 'make src' is the same as just typing
make. 'make doc' runs javadoc on the source files, this works only for
files in a package. 'make clean' removes class files and other
temporary files. 'make jar' creates a jar file with all class files
(and other files of your choice, see the JAR_OBJS variable in the
Makfile). 'make install' will tell you how to install a jar file or
class files. 'make help', shows a help text with available
targets. And finally 'make depend' creates a dependency graph for the
class files. (The dependency graph will be put in a file called
I<makefile.dep>, which is included in the Makefile)

B<mmake> is really just a perl-wraper around a Makefile template.  In
previous versions, perl played a much bigger role, but now, almost all
the work is left to the Makefile itself.

After running mmake, you will get a Makefile in the directory from
where you started the program. The Makefile will be able to handle
java files in current and in any sub-directories.

A nice difference from previous versions is that you dont't have to
run mmake each time you add a new java file. You can add as many new
java files as you like, the Makefile will find them. This is true as
long as you don't add a new package. In that case, you must either run
mmake again or update the PACKAGE variable in the Makefile, because
the Makefile uses this variable to find directories with java files.

mmake is now able to create a makefile dependency graph for your java
files. To do this, it need the I<jikes> compiler from IBM. Get jikes
from B<http://www.ibm.com/java/tools>. Anyhow, you would be a lot
happier with jikes, since it's much faster than javac. (When you have
jikes, patch this script, and replace the default java compiler with
jikes, instead of javac)


=head1 USING THE C-PREPROCESSOR

This is excellent for managing projects with several different
versions. The idea behind using the C preprocessor with Java is to be
able to manage different version in an easy way. This is done by using
CPP conditionals statments in the source files. I would strongly
advise you not to use CPP to redefine the Java language itself

To use the C preprocessor together with Java, change the name of the
source files you want to preprocess, from <filename>.java to
<filename>.xjava. The Makefile have a rule to build .class files from
.xjava files.

It is B<not> nececarry to change every file from .java to .xjava. The
Makefile will behave well and consistent in an environment with both
.java and .xjava files. (E.g. 'make clean' will only remove .java
files that was created from a .xjava file. Other java files will of
course I<not> be removed.)



You can now use cpp Conditionals in Your Java-code, for example, as
follows:

    #ifdef JAVA1_1
       [code1]
    #else
       [code2]
    #endif

Where the JAVA1_1 label in the above example is tested against the
VERSION variable in the Makefile. That is, if the VERSION variable is
JAVA1_1 then [code1] would be compiled and [code2] left out. Likewise,
if VERSION is something else, then [code2] would be compiled and
[code1] left out of the result .class file.

=head1 DEPENDENCIES

mmake will need the following:

=over 4

=item * 

Gnu make

=item * 

Perl 5.x

=item * 

Probably Gnu versions of find and install

=back

=head1 AUTHOR

Jan-Henrik Haukeland <hauk@tildeslash.com>

=head1 CVS INFO

$Id: mmake,v 1.16 1998/10/16 11:36:27 hauk Exp $

=cut

use strict;
use vars qw($opt_d);
use Getopt::Std;

require 5.000;                   # Need this perl version at least

($::prog = $0)=~   s,.*/,,;      # This Program name (usually 'mmake')
my $M=             "Makefile";   # The Java Makefile
my @packages=      ();           # Array holding packages, i.e. subdirectories 
my $toplevel=      "";           # Defined if toplevel java files
my $useCPP=        "No";         # Default no preprocessor
my $useJar=        "No";         # Default no jar file

# Parse command line options
$opt_d= undef;                   # Use defaults;
getopts("d") || die "Usage: $::prog [ -d ]\n";


# ---------------------
# Assign macro defaults
# ---------------------
my $javac=        "javac"; 
my $jflags=       "";
my $javadoc=      "javadoc";
my $docdir=       "./doc";
my $jdocflags=    "-version -author";
my $jar=          "jar";
my $jarflags=     "cvf0";
my $jarfile=      "";
my $jarinstalldir="";
my $installdir=   "";
my $cpp=          "cpp";
my $cppflags=     "-C -P";


if (-t and ( !$opt_d )) {
    # Let the user override the defaults
    print "Give Makefile variables or just type [enter] for default\n\n";
    $javac=         getline("JAVAC",   $javac);
    $jflags=        getline("JAVAC flags", $jflags);
    $javadoc=       getline("JAVADOC", $javadoc);
    $docdir=        getline("JAVADOC dir.",  $docdir);
    $jdocflags=     getline("JAVADOC flags", $jdocflags);
    $installdir=    getline("INSTALL dir. for class files", $installdir);    

    $useJar=        getline("Use Jar [y|n]?", $useJar);
    if($useJar =~ /^y/i) {
      $jar=           getline("JAR", $jar);
      $jarflags=      getline("JAR flags", $jarflags);
      $jarfile=       getline("JAR File name (basename only)", $jarfile);
      $jarinstalldir= getline("JAR FILE INSTALL dir", $jarinstalldir);    
    }

    $useCPP=        getline("Use CPP [y|n] ?", $useCPP);
    if($useCPP =~ /^y/i) {
	$cpp=      getline("CPP", $cpp);
	$cppflags= getline("CPP flags", $cppflags);
    }

    print "\n";
}


# Locate the java files/packages
find_packages();
die "No java source files found\n" unless @packages or $toplevel;

# If an old Makefile exists, rename it
if (-f $M) {
    rename($M, "$M.old") or
      die "$::prog: Cannot rename local Makefile.\n";
}

# Then create the new makefile
open(MAKEFILE, ">$M") || die "$::prog: Cannot create '$M': $!\n";


print MAKEFILE <<EOT;
#
# Makefile created at @{[scalar localtime]}, by $::prog
#

# Programs (with common options):
SHELL		= /bin/sh
RM              = rm -f
MV              = mv -f
SED		= sed
XARGS		= xargs
CAT		= cat
FIND            = find
CPP		= $cpp $cppflags

INSTALL         = install
INSTALL_PROG    = \$(INSTALL) -m \$(MODE_PROGS)
INSTALL_FILE    = \$(INSTALL) -m \$(MODE_FILES)
INSTALL_DIR     = \$(INSTALL) -m \$(MODE_DIRS) -d

# Install modes 
MODE_PROGS      = 755
MODE_FILES      = 644
MODE_DIRS       = 755

# Build programs
JAVAC           = $javac
JAVADOC         = $javadoc
JAR             = $jar

# Build flags
JAVAC_FLAGS     = $jflags
JAVADOC_FLAGS   = $jdocflags
JAR_FLAGS       = $jarflags
JIKES_DEP_FLAG	= +M


# Where to start installing the class files
CLASS_LIBDIR	= $installdir

# The directory to install the jar file in
JAR_LIBDIR	= $jarinstalldir

# The directory to install html files generated by javadoc
DOCDIR          = $docdir


# The dependency graph file
MAKEFILE_DEPEND	= makefile.dep

# The name of the jar file to install
JAR_FILE        = $jarfile

# 
# The VERSION variable below should be set to a value 
# that will be tested in the .xjava code. 
# 
VERSION		= CHANGE_ME


# ------------------------------------------------------------------- #

EOT


# Print the package list
print MAKEFILE "
# Packages we should compile
PACKAGES = ", 
  eval { 
    "\\\n\t" . join(" \\\n\t", @packages) if defined @packages;
  }, "\n\n\n\n";


print MAKEFILE <<EOT;

# A marker variable for the top level directory
TOPLEVEL        = .

# Subdirectories with java files:
JAVA_DIRS	= \$(subst .,/,\$(PACKAGES)) \$(TOPLEVEL)

# All the .xjava source files:
XJAVA_SRC	= \$(foreach dir, \$(JAVA_DIRS), \$(wildcard \$(dir)/*.xjava))

# All the xjava files to build
XJAVA_OBJS	= \$(XJAVA_SRC:.xjava=.java)

# All the .java source files:
JAVA_SRC	= \$(foreach dir, \$(JAVA_DIRS), \$(wildcard \$(dir)/*.java))
JAVA_SRC	:= \$(JAVA_SRC) \$(XJAVA_OBJS)

# Dependency files:
DEPEND_OBJS      = \$(JAVA_SRC:.java=.u)

# Objects that should go into the jar file. (find syntax)
JAR_OBJS         = \\( -name '*.class' -o -name '*.gif' -o -name "*.au" \\)

# All the .java source files we should build:
JAVA_OBJS	= \$(XJAVA_OBJS:.java=.class) \$(JAVA_SRC:.java=.class)

# All the java .class files we should install (including inner classes):
JAVA_INSTALL_OBJS= \$(foreach dir, \$(JAVA_DIRS), \$(wildcard \$(dir)/*.class))

# ------------------------------------------------------------------- #


# Courtesy reint\@sys.sol.no:
# Used in \$(foreach ...) to check exit value and add a newline in the
# shell commands.  Keep exactly as it is, including the empty line!
define check-exit
|| exit 1

endef

define check-exit-or-clean
|| { \$(RM) \$@; exit 1; }

endef

# -----------
# Build Rules
# -----------

%.java: %.xjava
	\$(CPP) -D\$(VERSION) \$< \$@

%.class: %.java
	\$(JAVAC) \$(JAVAC_FLAGS) \$<

%.jar: \$(JAVA_OBJS)
	\$(FIND) \$(TOPLEVEL) \$(JAR_OBJS) -print | \$(XARGS) \\
	\$(JAR) \$(JAR_FLAGS) \$(JAR_FILE) 

%.u: %.java
	\$(JAVAC) \$(JIKES_DEP_FLAG) \$<


# -------
# Targets
# -------

.PHONY : clean all doc jar install src


all:	src

src:	\$(JAVA_OBJS)

help:
	\@echo "Usage: make [ src | jar | install | doc | clean | depend ]"

install:
	\@echo "Run 'make install-jar' to install a jar file, or run "
	\@echo "'make install-classes' to install all classes"


ifneq (\$(strip \$(JAR_FILE)),)
jar:  \$(JAR_FILE)

install-jar: \$(JAR_FILE)
	\$(INSTALL_DIR) \$(JAR_LIBDIR)
	\$(INSTALL_FILE) \$(JAR_FILE) \$(JAR_LIBDIR)
else
install-jar jar: 
	\@echo "You must specify a name for the jar file before running"
	\@echo "install-jar or jar. See the JAR_FILE variable in the Makefile"
endif


ifneq (\$(strip \$(CLASS_LIBDIR)),)
install-classes:: \$(JAVA_OBJS)
	\$(INSTALL_DIR) \$(CLASS_LIBDIR)
	\$(foreach dir, \$(JAVA_DIRS), \\
		\$(INSTALL_DIR) \$(CLASS_LIBDIR)/\$(dir) \$(check-exit))
	\$(foreach file, \$(JAVA_INSTALL_OBJS), \\
		\$(INSTALL_FILE) \$(file) \$(CLASS_LIBDIR)/\$(file) \\
	\$(check-exit))
else
install-classes: 
	\@echo "Install dir for classes is not defined. See CLASS_LIBDIR"
endif


ifeq (\$(findstring jikes,\$(JAVAC)),jikes)
depend: \$(DEPEND_OBJS)
	( \$(CAT) \$(DEPEND_OBJS) | \$(SED) '/java/d' > \$(MAKEFILE_DEPEND); \\
	  \$(RM) \$(DEPEND_OBJS); )
else
depend: 
	\@echo "You must use the jikes compiler to create a dependency graph"
endif


ifneq (\$(strip \$(PACKAGES)),)
doc:	\$(JAVA_SRC)
	\$(JAVADOC) -d \$(DOCDIR) \$(JAVADOC_FLAGS) \$(PACKAGES)
else
doc:
	\@echo "You must put your source files in package(s) to run"\\
	       "make doc"
endif


clean::
	\$(FIND) . \\( -name '*~' -o -name '#*' \\) -exec \$(RM) {} \\;
	\$(FIND) . -name '*.class' -exec \$(RM) {} \\;


ifeq (\$(shell test -d \$(DOCDIR) && echo "true"),true)
clean::
	\$(FIND) \$(DOCDIR) -name '*.html' -exec \$(RM) {} \\;
endif

ifneq (\$(strip \$(XJAVA_SRC)),)
clean::
	\$(RM) \$(XJAVA_OBJS)
endif



# ----------------------------------------
# Include the dependency graph if it exist
# ----------------------------------------
DEPEND	= \$(shell test -r \$(MAKEFILE_DEPEND) && echo "true")
ifeq (\$(DEPEND),true)
	include \$(MAKEFILE_DEPEND)
endif

EOT

close(MAKEFILE);

print "'$M' created\n";

exit(0);


# ------------------------------------------------------------------------- # 
# ----------------------------- Subroutines ------------------------------- #
# ------------------------------------------------------------------------- # 

sub getline($$)
{
    my $key= shift;
    my $dir= shift;
    my $j;
    print "$key [$dir]: ";
    chomp($j= <STDIN>);
    return ($j =~ /\w/ ? $j : $dir);
}


sub find_packages()
{
  my %unique= ();
  my $cmd= sprintf("%s%s", 
		   "find . \\( -name \"*.java\" -o -name \"*.xjava\" \\) ",
		   "-printf \"%h\n\" 2>/dev/null |");

  # A filehandler containing directories with java source files
  open(JAVADIR, $cmd) ||
    die "$::prog: Can't run the \"find(1)\" command: $!\n";
  
  # Get the directories
  while (<JAVADIR>)
  {
    chomp;
    s,^./,,;
    s,/,.,g;
    $unique{$_}= undef if $_ =~ /\w+/;
    $toplevel= "."     if $_ =~ /\./;
  }
  close(JAVADIR);
  @packages= keys(%unique);
}

