#! /bin/csh
#
#  Configure C-shell scripts for src2www
#  Usage:  doconfigure script [script script ... ]
#       Reads from script.src, writes to script, saves
#       old version if any in script.OLD
#
#  Alternate use: doconfigure -deconfigure script [script ... ]
# 	(Used to booby-trap unconfigured scripts for a distribution)
##
#set echo  ## For debugging

if ($#argv < 1) then
  echo "Usage:  configure script [script ...]"
  exit(1);
endif

# Chicken and egg problem --- how do we configure this script to find a 
# suitable version of awk?  Assuming we are running within the same directory
# as the configuration file, we can just suck it in.
# 
if (-r Configuration ) then
   source Configuration
else
   echo 'Could not find file "Configuration"'
   echo 'Edit file Configuration.src and save as Configuration'
   exit 1;
endif

##
## Trim extraneous comments from the configuration file
##
rm -f ,Configuration.trimmed
${awk}  '/^[ \t]*##-/ { next; } \
 1 { print; }' <Configuration >,Configuration.trimmed

#
# We want our scripts to self-destruct if they have not been
# configured.  The -unconfigure flag tells us to set the alarm.
#
set shiva = creator
switch ($1:q)
   case -deconfigure: 
	   set shiva = destroyer
	   shift
endsw

## I think the following should no longer be needed, since I will
## be editing only the script.src files and not the real script files.
## I'll leave it in temporarily, until I know the new configuration 
## scheme is working. 
## 

cat >! ,bomb <<xxEOFxx
echo "Script  has not been configured"
echo 'Edit file "Configuration.src", save as "Configuration"'
echo '  and then type "make configure" '
echo '  (optionally followed by "make install" if you are '
echo '   installing in a different directory)'
exit(1)
xxEOFxx

while ($#argv >= 1) 

foreach script ($*) 

if (-f $script.src) then
   echo "Configuring $script based on $script.src"
else 
   echo "Base script $script.src is not present .. skipping $script"
   continue; 
endif 

set oldcopy = $script.OLD
set tmpcopy = ,$script.$$

if ($shiva == destroyer) then
  echo "Deconfiguring $script"

${awk} 'BEGIN { copying = 1 }\
/^#BEGIN CONFIGURE/ {  copying = 0; print; system("cat ,bomb"); }\
/^#END CONFIGURE/ {  copying = 1; } \
 copying == 1 { print; } ' <$script >$tmpcopy

else 

${awk} 'BEGIN { copying = 1 }\
/^#BEGIN CONFIGURE/ {  copying = 0; print; \
  system("cat ,Configuration.trimmed"); }\
/^#END CONFIGURE/ {  copying = 1; } \
copying == 1 { print } ' <$script.src >$tmpcopy

endif

## Note: there is a bug in some nawk implementations that will not
## recognized "copying" as boolean expression without "==1"
##

${rm} -f $oldcopy
if (-f $script) then 
   mv $script $oldcopy
   echo "Old configuration of $script saved as $oldcopy"
endif
mv $tmpcopy $script
chmod a+x $script
chmod a-w $script

echo "Configuration of $script completed"

end

$rm ,bomb
$rm ,Configuration.trimmed
echo "Configurations finished" 

