#!/bin/csh -f

# rsync backup sometimes modifies read times on a file.  This script
# will collect read times for a filespec or restore read times from a
# previously collected file of read times.

# daw; 6/29/20

switch (`uname -s``uname -r`)
case SunOS5*:
    set FIND = /usr/local/gnu/bin/find
    set TOUCH = /usr/local/gnu/bin/touch
	breaksw
case Linux*:
    set FIND = /usr/bin/find
    set TOUCH = /bin/touch
	breaksw
default:
	exec echo ${0}: does not run on `uname -s` `uname -r`
endsw

set DEBUG

while($#argv)
	switch ("$1")
	case -d:
		set DEBUG = /bin/echo
#		shift
#		breaksw
# fall through to verbose
	case -vv:
		set VVERBOSE
# fall through to verbose
	case -v:
		set VERBOSE
		shift
		breaksw
	case -r:
		set RESTORE
		shift
		breaksw
	default:
	    if (! $?FILESPEC) then
		set FILESPEC = "$1"
		shift
		breaksw
	    endif
		set DQ = '"'
		exec echo ${0}: "What do I do with $DQ$1$DQ?"
	endsw
end

if (! $?FILESPEC) exec echo $0 "<filespec>"

if ("$DEBUG" != "") echo `date +%T` FILESPEC = "$FILESPEC"

set DQ = '"'
set BASE = `basename $0`
set TMP = /tmp/$BASE
set EFILESPEC = `echo "$FILESPEC" | sed -e 's;/;_SL_;g' -e 's;*;_AST_;g' -e 's;?;_QM_;g'`
set RTFILE = $TMP.$EFILESPEC

/bin/ls -d $FILESPEC |& grep -v "No match" > /dev/null
if ($status) exit

if ("$DEBUG" != "") echo `date +%T` RTFILE = "$RTFILE"

if ($?RESTORE) goto restore

$FIND $FILESPEC -exec /bin/ls -lu {} \; > "$RTFILE"

exit 0

restore:

set FILES = `/bin/ls -ru $FILESPEC`

set VVEXP
foreach FILE ( $FILES )
    set ORTIME = `grep "$FILE"'$' $RTFILE | awk '{print $6,$7,$8}'`
    if ("$ORTIME" != "") then
	set NRTIME = `/bin/ls -lu $FILE | awk '{print $6,$7,$8}'`
	if ("$NRTIME" != "$ORTIME") then
#	    if ($?VERBOSE) echo Restoring read time on $FILE
	    if ($?VVERBOSE) set VVEXP = "($NRTIME => $ORTIME)"
	    if ($?VERBOSE) echo Restoring read time on $FILE$VVEXP
$DEBUG	     $TOUCH --date="$ORTIME" $FILE
	else
	    break
	endif
    endif
end


