#!/bin/tcsh -f

# Make $1.e by decrypting all files with the same root as $1 to
# corresponding files on a temporary subdirectory, making $1 there,
# and then encrypting new files back onto the main directory.

set debug = 0

umask 66

set target = $1
set base = `expr $1 : '\([^.]*\)'`
set basebase = `expr $base : '\(.*\)-soln'`

if ("$basebase" != "") then
  set noglob
  set base = "{$base,$basebase}"
  unset noglob
endif

if ($debug) echo "target: $target, base: $base"

shift
set key = "$*"
if ("$key" == "") then
  echo "Enter key:"
  set key = "$<"
endif

touch $base.dummy.e

foreach file ($base.*.e)
  if ("$file" !~ *~*) then
    set tempfile = $file:r
    if ($debug) echo "file: $file, tempfile: $tempfile"
    if (-e $tempfile) then
      set tempfile = `find $tempfile -newer $file -print`
      if ("$tempfile" != "") then
        echo "makecry: Warning: $file not decrypted since $tempfile is newer."
        continue
      else
        set tempfile = $file:r    
      endif
    endif
    crypt "$key" <$file >$tempfile
    touch -r $file $tempfile
  endif
end

make $target

if ($debug) ls -alt $base.*

foreach tempfile ($base.*)
  if ("$tempfile" !~ *.e && "$tempfile" !~ *~*) then
    set file = $tempfile.e
    if ($debug) echo "tempfile: $tempfile, file: $file"
    if (-e $file) then
      set file = `find $file -newer $tempfile -print`
      if ("$file" != "") then
        echo "makecry: Warning: $tempfile not encrypted since $file is newer."
        continue
      else
        set file = $tempfile.e
      endif
    endif
      crypt "$key" <$tempfile >$file
      touch -r $tempfile $file
      rm $tempfile
  endif
end

rm -f $base.dummy $base.dummy.e
