#!/bin/csh -f

# This script preserves for later restore
#	/etc/ssh/*.pub		# and corresponding private key file
#	/<hostname>/local	# unless "-sl" is specified

# Quick script to preserve stuff while machine is being reinstalled.

# daw; 8/12/10

# Allow /hostname/local to be skipped, should it be large enough to
# preserve by rync previously.  7/10/13

# allow specification of different hostname to restore from.  7/7/15

switch (`uname -s``uname -r`)
case Linux[23]*:
	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 -v:
		set VERBOSE
		shift
		breaksw
	case -r:
		set RESTORE
		shift
		breaksw
	case -sl:
		set SKIPLOCAL
		shift
		breaksw
	default:
	    if (! $?HN) then
		set HN = $1
		shift
		breaksw
	    endif
		set DQ = '"'
		exec echo ${0}: "What do I do with $DQ$1$DQ?"
	endsw
end

set KVT = /koko/var/tmp
if (! $?HN) set HN = `hostname | sed 's;\.[Rr][Uu][Tt][Gg][Ee][Rr][Ss]\.[Ee][Dd][Uu];;'`
set PDIR = $KVT/$HN

if (! $?RESTORE) then
    if ($?VERBOSE) echo `date +%T` Building \"preserve\" directory "($PDIR)"

    if (! -e $KVT) exec echo $KVT does not exist
    if (-e $PDIR)  exec echo $PDIR already exists

    $DEBUG /bin/mkdir $PDIR
    $DEBUG /bin/chmod 700 $PDIR
else
    if (! -e $PDIR)  exec echo $PDIR does not exist
endif

if ($?VERBOSE) echo `date +%T` SSH keys

if (! $?RESTORE) then
    $DEBUG /bin/mkdir $PDIR/etc
    $DEBUG /bin/chmod --reference=/etc $PDIR/etc

    $DEBUG /bin/mkdir $PDIR/etc/ssh
    $DEBUG /bin/chmod --reference=/etc/ssh $PDIR/etc/ssh

    foreach FILE ( /etc/ssh/*.pub )
	set OFILE = `echo $FILE | sed 's;\.pub;;'`
	$DEBUG /bin/cp -p $OFILE{,.pub} $PDIR/etc/ssh
    end
else
    set TSTMP = .`date +%y%m%d`
    foreach FILE ( $PDIR/etc/ssh/*.pub )
	set OFILE = `echo $FILE | sed 's;\.pub;;'`
	set LFILE = `echo $FILE | sed "s;$PDIR;;"`
	set LOFILE = `echo $OFILE | sed "s;$PDIR;;"`
	if (-e $LFILE) $DEBUG /bin/mv $LFILE{,$TSTMP}
	$DEBUG /bin/cp -p {$PDIR,}$LFILE
	if (-e $LOFILE) $DEBUG /bin/mv $LOFILE{,$TSTMP}
	$DEBUG /bin/cp -p {$PDIR,}$LOFILE
    end
endif

if ($?VERBOSE) echo `date +%T` /hostname/local

if (-e /$HN/local ) then

    if ($?SKIPLOCAL) then
	if ($?VERBOSE) echo '   ' /$HN/local skipped
    else
	if (! $?RESTORE) then
	    $DEBUG /bin/mkdir $PDIR/$HN
	    $DEBUG /bin/chmod --reference=/$HN $PDIR/$HN
	    
	    $DEBUG /bin/mkdir $PDIR/$HN/local
	    $DEBUG /bin/chmod --reference=/$HN/local $PDIR/$HN/local
	    
	    $DEBUG ~watrous/Sys/rcpdir {,$PDIR}/$HN/local
	else if (-e $PDIR/$HN/local) then
	    $DEBUG ~watrous/Sys/rcpdir {$PDIR,}/$HN/local
	else
	    if ($?VERBOSE) echo '   ' $PDIR/$HN/local does not exist
	endif
    endif
    
else
    echo '   ' /$HN/local does not exist
endif

if ($?VERBOSE) echo `date +%T` Done
