#!/bin/sh
# Script to build .jnlp files for use with Web Start.  See $PTII/mk/jnlp.mk
#
# @author: Christopher Hylands
# @version: $Id: mkjnlp,v 1.20 2006/12/19 03:48:00 cxh Exp $
#
# Copyright (c) 2001-2006 The Regents of the University of California.
# 	All Rights Reserved.
#
# Permission is hereby granted, without written agreement and without
# license or royalty fees, to use, copy, modify, and distribute this
# software and its documentation for any purpose, provided that the
# above copyright notice and the following two paragraphs appear in all
# copies of this software.
#
# IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
# THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
# PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
# CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
# ENHANCEMENTS, OR MODIFICATIONS.
#
# 						PT_COPYRIGHT_VERSION_2
# 						COPYRIGHTENDKEY
# 

if [ $# -lt 4 ]; then 
    echo "Usage: mkjnlp jnlpfile basedirectory number_of_jars_to_load_eagerly mainjar otherjars . . ."
    exit 5
fi

jnlpfile=$1
eagerjars=$2
basedirectory=$3
mainjar=$4
shift; shift; shift; shift
tmpfile=/tmp/mkjnlp.$$

otherjars="$@"

if [ ! -d $basedirectory ]; then
    echo "$0: '$basedirectory' does not exist or is not a directory"
    exit 5
fi

# Cygwin might have /cygdrive/c/WINDOWS/system32/sort in the path
# before /usr/bin/sort

SORT=/usr/bin/sort

for file in $otherjars
do
    if [ ! -f $basedirectory/$file ]; then
	echo "$0: WARNING: '$basedirectory/$file' could not be found,"
	echo "     which means that the sizes in the .jnlp file will be wrong"
    fi	
    # Use ls -lg because Cygwin ls -l includes the group and
    # Under Cygwin, group names could have spaces: "Domain Users"
    # Solaris 8 /usr/ucb/ls -l does not
    otherjarssizes="$otherjarssizes `/bin/ls -l $basedirectory/$file | awk '{for (i=3;i<NF;i++) {if ($i ~ /^[0-9]*$/) {print $i; exit}}}'`"

    # Determine what packages are in the jar file
    echo "$file"
    packages=`jar -tf $basedirectory/$file |
	grep -v '/$' | grep -v META | grep -v JNLP-INF |
	awk -F / '{
		   for(i = 1; i < NF; i++) {
			if (i == 1) {
				printf("%s", $i)
			} else {
				printf(".%s", $i)
			}
		   } 
                   printf(".*\n")
	}' | $SORT | uniq |
	awk '{if (NR > 1 && NR < 50) {
		printf(",%s", $0)
	     } else {
	        printf("%s",$0)
             }
	}' - `
    echo "packages: `echo $packages| wc` $packages"
    otherjarspackages="$otherjarspackages $file:${packages}"
done

echo $otherjarspackages | awk -F " " '{for(i=1;i<NF;i++) print i, $i}'
otherjarspackages=""
# Read in the jar files and generate jar and package lines for them
# * We need to take in to account that one of the jar files
# will need main="true"
# * A lib/foo.jar file provides classes in the foo package
awk '{
    if ($0 ~ /<!-- Start Jars -->/) {
	sawStartJars = 1
	print $0
	printf("\t<!-- The list of jars below is automatically generated\n") 
	printf("\t     by $PTII/bin/mkjnlp -->\n");

	njars = split(otherjars, jars, " ") 
	nsizes = split(otherjarssizes, sizes, " ") 
        npackages = split(otherjarspackages, packages, " ");
	if (njars != nsizes) {
	    error "njars != nsizes (" njars " != " npackages ")"
	}
	if (njars != npackages) {
	    error "njars != npackages (" njars " != " npackages ")"
	}

	for(n = 1; n <= njars; n++) {
	    ndirs = split(jars[n], dirs, "/")
	    # If the jar file is in the lib directory then skip 
	    # the lib part.
	    if (dirs[1] == "lib" && ndirs == 2) {
		split(dirs[2],filename,".")
		package = filename[1]
                part = package
	    } else {
    		package = dirs[1]
                part = package
		# Skip the .jar part at the end.
		for (m = 2; m < ndirs; m++) {
		    package = package "." dirs[m]
		    part = part "_" dirs[m]
		}
	    }
	    #printf("\t<jar href=%c%s/%s%c\n\t\tpart=%c%s%c", 34, basedirectory, jars[n], 34, 34, part, 34)
            printf("\t<jar href=%c%s/%s%c", 34, basedirectory, jars[n], 34);
	    printf("\n\t\tsize=%c%s%c", 34, sizes[n], 34)
	    if (jars[n] == mainjar) {
		printf("\n\t\tmain=%ctrue%c", 34, 34)
	    } else {
                # Convert eagerjars to an integer by adding 0
	        if (n <= (eagerjars+0)) {
		    # Load the eagerjars number of jars eagerly.
		    printf("\n\t\tdownload=%ceager%c", 34, 34)
		} else {
		    # Load everything else lazily
   	            printf("\n\t\tpart=%c%s%c", 34, part, 34)
		    #printf("\n\t\tdownload=%clazy%c", 34, 34)
		    printf("\n\t\tdownload=%ceager%c", 34, 34)
		}
	    }
	    printf("/>\n")
            if (n > (eagerjars+0)) {
                # package only makes sense for lazy jars

                split(packages[n], fileAndPackages, ":")
                np = split(fileAndPackages[2], p, ",");
                for(i = 1; i <= np; i++) {
                    printf("\t<!-- %d %s -->\n", n-eagerjars, fileAndPackages[1]);
	            printf("\t<package name=%c%s%c\n\t\tpart=%c%s%c recursive=%ctrue%c/>\n", 34, p[i], 34, 34, part, 34, 34, 34)
                }
                # Substitute in different package names for various files
                #if (part == "mapss") {
                #    package = "mapss"
                #} else if (part == "ptcolt") {
                #    package = "edu.cornell.lassp"
                #} else if (part == "ptCal") {
                #    package = "caltrop"
                #}
	        #printf("\t<package name=%c%s.*%c\n\t\tpart=%c%s%c recursive=%ctrue%c/>\n", 34, package, 34, 34, part, 34, 34, 34)
            }
	}
    } else {
        if (sawStartJars != 1) {
	    print $0
	} else {
	    if ($0 ~ /<!-- End Jars -->/) {
		print $0
		sawStartJars = 0
	    }
	}
    }
}' basedirectory=$basedirectory \
    eagerjars=$eagerjars \
    mainjar=$mainjar \
    otherjars="$otherjars" \
    otherjarssizes="$otherjarssizes" \
    otherjarspackages="$otherjarspackages" \
    $jnlpfile > $tmpfile

#diff $tmpfile $jnlpfile
cp $tmpfile $jnlpfile
rm -f $tmpfile
