#!/bin/csh -f

@ errorflag = 0
@ removeflag = 0

if ($#argv > 2 || $#argv < 1) then
    @ errorflag = 1
else if ($#argv == 2) then
    if ("$argv[1]" != "-r") @ errorflag = 1
    @ removeflag = 1
    set file = $argv[2]
else if ("$1" == "-") then
    @ errorflag = 1
else
    set file = $argv[1]
endif

if ($errorflag == 1) then
    echo "usage: cpio_collapse [-r] <cpio_file>"
    echo "       -r: removes the contents file and the expanded directory"
    echo
    echo "cpio_collapse will collapse a directory that was previously extracted"
    echo "from a cpio file using cpio_expand"
    exit
endif

# if the user tries to collapse the directory, it should work too
set script = 's/^cpio\.\(.*\)\.dir$/\1/'
set file = `echo $file | sed -e "$script"`

if ( ! -d cpio.${file}.dir || ! -f cpio.${file}.contents ) then
    echo cpio_collapse requires both:
    echo cpio.${file}.dir 
    echo cpio.${file}.contents
    echo that were generated by cpio_expand in order to work correctly
    exit
endif

if ( -f $file) then
    set backupfile = ${file}.bkp
    @ version = 2
    while ( -f $backupfile)
	@ version = $version + 1
	set backupfile = ${file}.bkp$version
    end
    mv $file $backupfile
    echo old $file stored as $backupfile
endif

cd cpio.${file}.dir
cat ../cpio.${file}.contents | cpio -oO ../$file -H odc
cd ..

echo collapsed cpio.${file}.dir into $file

if ($removeflag == 1) then
    rm -rf cpio.${file}.contents cpio.${file}.dir
    echo removed cpio.${file}.contents and cpio.${file}.dir
endif
