#! /bin/csh -f
#
# USAGE
#     cd ~/projects/work/...; copy-work-to-alpha.csh
#
# DESCRIPTION:
#     This script uses tar to copy an entire projects work directory to its
#     corresponding projects alpha directory.  Emacs backup and other
#     unnecessary files are not copied.
#
# SEE ALSO:
#     ./update-work-to-alpha.csh, which updates only changed files.
#
#

# Ensure that we're in a projects/work dir.
set c = `pwd`
set d = $c:t
cd ..
set w =  `pwd`
set w = $w:t
cd ..
set p =  `pwd`
set p = $p:t
if ( ! ( ($w == "work") && ($p == "projects") ) ) then
    echo "Must be in a projects/work subdirectory."
    exit 1
endif

# Go back down to the src dir.
cd $c

# Find all the non-junk files with tar.
find . -type f \
    \( \! -name '*~' \) \( \! -name '.*~' \) \( \! -name '#*' \) \
    -print |& tee .copy-to-alpha.out

# Do the copying and logging, if there are any files to copy.
if (! -z .copy-to-alpha.out) then

    # Update the copy log file with the current date and append the list of 
    # files to be copied.
    echo "" >> .copy-to-alpha.log
    echo `date` >> .copy-to-alpha.log
    cat .copy-to-alpha.out >> .copy-to-alpha.log

    # Unconditionally nuke the dest dir (or file or link), and make a new one.
    chmod -R u+w ../../alpha/$d
    rm -rf ../../alpha/$d
    mkdir ../../alpha/$d

    # Do the deed with tar.
    tar cf - `cat .copy-to-alpha.out` | (cd ../../alpha/$d; tar xvf -)

    # Update the files who's modification dates record the date of this copy as
    # well as the two previous copies (or updates).  Note that copy and update
    # both touch the same date files.
    if (-e .last-copied-to-alpha) then
        mv .last-copied-to-alpha .previously-last-copied-to-alpha
    else
        touch .last-copied-to-alpha .previously-last-copied-to-alpha
    endif

    if (-e .copied-to-alpha) then
        mv .copied-to-alpha .last-copied-to-alpha
    else
        touch .last-copied-to-alpha
    endif

    touch .copied-to-alpha
else
    echo "Nothing to copy."
endif

# Finish things up by making all alpha files read only.
cd ../../alpha/$d
chmod -R a-w .
