#! /bin/sh -e

# generate a new dcc_conf file from an existing file

# Copyright (c) 2004 by Rhyolite Software
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND RHYOLITE SOFTWARE DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL RHYOLITE SOFTWARE
# BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
#	Rhyolite Software DCC 1.2.47-1.11 $Revision$

FNAME=dcc_conf

SUFFIX=new
OLD=
PROTOTYPE=$FNAME

USAGE="$0: [-x] [-i old] [-h homedir] [-s new-suffix] -p prototype"
while getopts "xi:h:s:p:" c; do
    case $c in
	x) set -x; DEBUG=-x;;
	i) OLD="$OPTARG";;
	h) DCC_HOMEDIR="$OPTARG";;
	s) SUFFIX="$OPTARG";;
	p) PROTOTYPE="$OPTARG";;
	*) echo "$USAGE" 1>&2; exit 1;;
    esac
done
shift `expr $OPTIND - 1 || true`
if test "$#" -ne 0 -o -z "$DCC_HOMEDIR" -o -z "$SUFFIX"; then
    echo "$USAGE" 1>&2
    exit 1
fi

if test ! -s "$PROTOTYPE"; then
    echo "prototype $PROTOTYPE does not exist" 1>&2
    exit 1
fi

if test -z "$OLD"; then
    OLD="$DCC_HOMEDIR/$FNAME"
fi
if test ! -f "$OLD"; then
    echo "$OLD does not exist" 1>&2
    exit 1
fi

TGT="$OLD-$SUFFIX"

awk -F= '(file1 == "") {
	    file1 = FILENAME;
	}
	/^[A-Z]/ {
	    if (file1 == FILENAME) {
		defined[$1] = 1;
		mem[$1] = $2;
	    } else {
		# on first line of second file, make compatibility adjustments
		if (!adjusted) {
		    adjusted = 1;
		    if (mem["DCCD_ENABLE"] == "") {
			defined["DCCD_ENABLE"] = 1;
			if (mem["SRVR_ID"] == "") {
			    mem["DCCD_ENABLE"] = "off";
			} else {
			    mem["DCCD_ENABLE"] = "on";
			}
		    }
		    # fix DCC_RUNDIR=@dcc_rundir@ bug in 1.2.14 and preceding
		    if (defined["DCC_RUNDIR"]) {
			    if(mem["DCC_RUNDIR"] == "@dcc_rundir@") {
				defined["DCC_RUNDIR"] = 0;
			    }
		    }
		}
		if (defined[$1]) {
		    print $1 "=" mem[$1];
		} else {
		    print $0;
		}
	    }
	}
	!/^[A-Z]/ && (FILENAME != file1) {
	    print $0;
	}' $OLD $PROTOTYPE >$TGT
