#!/bin/csh -f

if ( "${1}" == "-h" || "${1}" == "--help" ) then
    echo "TARDIR"
    echo "         written by Luke Abraham 2005/11/10 "
    echo "USEAGE:"
    echo " "
    echo "-h, --help                  prints this message"
    echo "no argument,-p,--pack       takes all the directories in the"
    echo "                            current directory and if they are full,"
    echo "                            tar.gz's them to dir.tgz, or if the"
    echo "                            directory is empty then it removes it"
    echo "-u,--unpack                 takes all tgz files in the current"
    echo "                            directory and unpacks them"
    exit 1
endif

# we are creating the tgz files.
if ( ${#argv} == 0 || "${1}" == "-p" || "${1}" == "--pack" ) then
    # get list of files
    set dirlist=`ls -F | grep /`
    echo $dirlist
    # are they a directory?
    foreach dirname ($dirlist)
	# yes they are
	if ( -d ${dirname} ) then
	    echo "=================================================="
	    echo "checking directory "${dirname}
	    # are they empty? - if no, tar and then remove.
	    set dircont=`ls -a ${dirname} | wc | awk '{print $1}'`
	    if ( "${dircont}" == 2 ) then # dir is empty
		# just remove empty directory
		echo "just removing empty directory "${dirname}
		echo "rmdir "${dirname}
		rmdir ${dirname}/
	    else #dir is full - tgz!
		set tarfile=${dirname}.tgz
		echo ${tarfile}
		echo "checking to see if tgz file exists"
		# does a .tar file already exist?
		if ( -e ${tarfile} ) then # yes - append
		    echo "appending tar file "${tarfile} "with directory "${dirname}
		    echo "tar --remove-files --gzip -uvf "${tarfile}" "$dirname
		    tar --remove-files --gzip -uvf ${tarfile} ${dirname}/
		else # no - create
		    echo "creating tar file "${tarfile} "from directory "${dirname}
		    echo "tar --remove-files --gzip -cvf "${tarfile}" "$dirname
		    tar --remove-files --gzip -cf ${tarfile} ${dirname}/
		endif
		echo "now removing empty directory "${dirname}
		echo "rmdir "${dirname}/
		rmdir ${dirname}/
	    endif
	endif
    end
# we are unpacking the tgz files
else if ( "${1}" == "-u" || "${1}" == "--unpack" ) then
    # get list of files
    set dirlist=`ls -F | grep tgz`
    echo $dirlist
    foreach dirname ($dirlist)
	echo "=================================================="
	echo "untaring "${dirname}
	echo "tar -xzf "${dirname}
	tar -xzf ${dirname}
    end
else
    echo "Incorrect useage. Please re-run with -h for help."
endif
echo "=================================================="