#!/bin/sh
#
# rexport --
#	retrying export with customs
#
# $Header: /usr/src/local/icsi/pmake/customs/RCS/rexport,v 1.10 2001/02/13 08:27:04 stolcke Exp $
#

usage() {
	echo "usage: $0 [-m] [-J numjobs] [-f] [-debug] [-same] [-exclusive] [-uselocal] [-attr value] ... command [args ...]" >&2
}

# allow as many file descriptors as possible for pmake
# (this command may fail in old versions of sh -- we ignore that)
ulimit -n `ulimit -H -n 2>/dev/null` >/dev/null 2>&1

set -e 

jobs=1
makemode=0

#
# parse options
#
attributes=
while [ $# -gt 0 ]; do
	case "$1" in
	-m)	makemode=1
		shift ;;
	-same)	attributes="$attributes SAME"
		shift ;;
	-exclusive)
		attributes="$attributes EXCLUSIVE"
		shift ;;
	-uselocal)
		attributes="$attributes USELOCAL"
		shift ;;
	-attr)	attributes="$attributes $2"
		shift; shift;;
	-debug)	debug=1
		shift ;;
	-f)	readfiles=1;
		shift ;;
	-J)	jobs="$2"
		shift; shift ;;
	-*)	usage
		exit 2 ;;
	*)
		break ;;
	esac
done

#
# parse command
#

mkfile=/tmp/export$$

trap "rm -f $mkfile; exit 1" 1 2 15

#
# create makefile
#
if [ "$#" -eq 0 -o "$readfiles" ]; then
	# read commands from files or stdin
	cat "$@"
else
	# use what's on the command line
	echo "$@"
fi | \
gawk '
NR == 1 {
	# always use /bin/sh for portability across platforms
	print ".SHELL: path=/bin/sh"
	print ".EXPORT:"
	print ".EXPORT: " attributes
	print ".BEGIN: .NOEXPORT"
	print "\t@/bin/rm -f " mkfile
	print ".MAIN: all"
	
	jobnum = 0;
}
NF > 0 {
	jobnum ++;

	job = ".job" jobnum;
	alljobs = alljobs " " job;

	# make sure shell variable expansion is preserved
	gsub("\\$", "$$");

	if (njobs > 1) {
		print job ": ; " $0;
	} else {
		print job ": ; @" $0;
	}
	if (makemode) {
		print "\t@touch " job;
	}
}
END {
	print "all:" alljobs;
	

	makeflags = "-L 0 -J " njobs
	if (jobnum == 0) {
		print "warning: empty command list" > "/dev/stderr";
	} else if (jobnum > 1) {
		makeflags = makeflags " -k";
	}
	print ".MAKEFLAGS: " makeflags
}
' makemode=$makemode attributes="$attributes" mkfile="$mkfile" njobs="$jobs" > $mkfile

if [ "$debug" ]; then
	cat $mkfile
	rm -f $mkfile
	exit
fi

# unset the user's default pmake environment
PMAKE=; export PMAKE

exec `dirname $0`/pmake -l -f $mkfile

