#!/bin/csh -fb
# (The "-fb" might need to be changed to "-f" on some systems)
#

if (! $?METAMAIL_TMPDIR) then
    set METAMAIL_TMPDIR=~
endif

set TREEROOT=${METAMAIL_TMPDIR}/m-prts-`whoami`
if ($#argv < 3 || $#argv > 4) then
    echo "Usage:  showpartial file id partnum totalnum"
    exit -1
endif
set file=${1:q}
# This next line is because message-id can contain weird chars
set id=`echo ${2:q} | tr -cd A-Za-z0-9_-\.\@`
@ partnum = ${3:q}
if ($#argv == 3 || ${4:q} == "") then
    @ totalnum = -1
else
    @ totalnum = ${4:q}
endif

if (! -d  ${TREEROOT:q})  then
    mkdir -m 0700 ${TREEROOT}
    if ($status) then 
        echo "mkdir -m 0700 ${TREEROOT} failed"
        exit -1
    endif
endif
if (! -d "${TREEROOT}/${id:q}") then 
    mkdir "${TREEROOT}/${id:q}"
    if ($status) then 
        echo mkdir "${TREEROOT}/${id:q}" failed
        exit -1
    endif
endif
cp ${file:q} "${TREEROOT}/${id:q}/${partnum}"
if ($status) then 
    echo cp ${file:q} "${TREEROOT}/${id:q}/${partnum}" failed
    exit -1
endif
if (${totalnum} == -1) then
    if (-e "${TREEROOT}/${id:q}/CT") then
	@ totalnum = `cat "${TREEROOT}/${id:q}/CT"`
    else
    	@ totalnum = -1  #GROSS HACK
    endif
else
    echo ${totalnum} >! "${TREEROOT:q}/${id:q}/CT"
endif
# Slightly bogus here -- the shell messes up the newlines in the headers
# If you put $MM_HEADERS in quotes, it doesn't help.
# if (${partnum} == 1) then
#     echo $MM_HEADERS > "${TREEROOT}/${id}/HDRS"
# endif
@ found = 0
@ ix = 1
set list=()
@ limit = ${totalnum}
if (${limit} == -1) set limit=25
while (${ix} <= ${limit})
    if (-e "${TREEROOT:q}/${id:q}/${ix}") then
	set list=(${list:q} ${ix})
	@ found ++
    endif
    @ ix ++
end
if (${found} == ${totalnum}) then
    cd "${TREEROOT}/${id:q}"
    cat ${list:q} > "${TREEROOT}/${id:q}/FULL"
#    cat "${TREEROOT}/${id:q}/HDRS" ${list} > "${TREEROOT}/${id:q}/FULL"
    rm ${list:q}
    echo "All parts of this ${totalnum}-part message have now been read."
    metamail -d  "${TREEROOT}/${id:q}/FULL"
    echo WARNING:  To save space, the full file is now being deleted.  
    echo You will have to read all ${totalnum} parts again to see the full message again.
    rm "${TREEROOT}/${id:q}/FULL"
    rm "${TREEROOT}/${id:q}/CT"
#    rm "${TREEROOT}/${id:q}/HDRS"
    cd
    rmdir "${TREEROOT}/${id:q}"
    rmdir "${TREEROOT}" >& /dev/null
else
    if (${totalnum} == -1) then
        echo "So far you have only read ${found} of the several parts of this message."
    else
        echo "So far you have only read ${found} of the ${totalnum} parts of this message."
    endif
    echo "When you have read them all, then you will see the message in full."
endif
    
