#!/bin/csh -f

# Test to see if we're running on windows NT
set CPIO = cpio
if ( $?OS ) then
    if ( $OS == Windows_NT || $OS == linux ) set CPIO = hcpio
endif
if ( $?OSTYPE ) then
    if ( $OSTYPE == Windows_NT || $OSTYPE == linux ) set CPIO = hcpio
endif

@ errorflag  = 0
@ prefixflag = 0
@ removeflag = 0

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

if ($errorflag == 1) then
    echo "usage: hcollapse [-r] [-p] <hip_file>"
    echo "       -r: removes the contents file and the expanded directory"
    echo "       -p: expects the 'cpio.' prefix in the contents and dir files"
    echo
    echo "hcollapse will collapse a directory that was previously extracted"
    echo "from a Houdini .hip file using hexpand"
    exit
endif

if ($prefixflag == 1) then
    # if the user tries to collapse the directory, it should work too
    set script1 = 's/^cpio\.//'
    set file = `echo $file | sed -e "$script1"`
    set prefx = cpio.
else
    set prefx = ""
endif

set filetest = $file

if ( ! -d ${prefx}${filetest}.dir || ! -f ${prefx}${filetest}.contents ) then
    # try with out the extension (in case the user specified the .dir)
    set filetest = $file:r
    if ( ! -d ${prefx}${filetest}.dir || ! -f ${prefx}${filetest}.contents ) then
	# Try with .hip in case they typed the root name 
	set filetest = $file.hip
	if ( ! -d ${prefx}${filetest}.dir || ! -f ${prefx}${filetest}.contents ) then
	    # Try .optype in case it is this root name.
	    set filetest = $file.optype
	endif
    endif
endif

if ( ! -d ${prefx}${filetest}.dir || ! -f ${prefx}${filetest}.contents ) then
    echo hcollapse requires both:
    echo ${prefx}${file}.dir 
    echo ${prefx}${file}.contents
    echo that were generated by hexpand in order to work correctly
    echo Perhaps you forgot to specify the -p option
    exit
endif

set file = $filetest

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

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

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

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