#! /bin/sh
#
# Written by andrey joukov
# (C) 1996 2:5020/337.13@fidonet.org
# Updated by christian.gennerat@alcatel.fr 1999
# beta version 2.0
#
DRAR=/usr/bin
RAR=$DRAR/rar
UNRAR=$DRAR/unrar # Prefer unrar (freeware)
#
# NOTE: rar ver 2.0 by Eugene Roshal
# ftp.elf.stuba.sk/pub/pc/pack
#

mcrarfs_list ()
{
     $UNRAR v -c- "$1" | gawk -v uid=${UID-0} '
BEGIN { flag=0; date="JanFebMarAprMayJunJulAugSepOctNovDec" }
/^-------/ { flag++; if (flag > 1) exit 0; next }
{
if (flag == 0) next
if ( !/ [0-9][0-9]:[0-9][0-9] /) str = $0  # there is no time spec in this line
else {
    if (str ~ /^\^/)
	str=substr(str, 2)
    split($4, a, "-")
    if (a[3] < 50)
	a[3] = 2000 + a[3]
    else
	a[3] = 1900 + a[3]
    if (index($6, "D") != 0)
	$6="drwxr-xr-x"
    else
	if (index($6, ".") != 0)
	    $6="-rw-r--r--"
    printf "%s   1 %-8d %-8d %8d %3s %2d %4d %s %s\n", $6, uid, 0, $1, substr(date, (a[2]-1)*3+1, 3), a[1], a[3], $5, str
}
}' 2>/dev/null
}

mcrarfs_copyin ()
{
# copyin by christian.gennerat@alcatel.fr
# preserve pwd. It is clean, but is it necessary?
    pwd=`pwd`
# Create a directory and copy in it the tmp file with the good name     
    mkdir $3.dir
    cd $3.dir
    di="${2%/*}"
# if file is to be written upper in the archive tree, make fake dir
    if test "$di" != "${2##*/}" ; then
        mkdir -p "$di" 
    fi
# (cp -p) to preserve date, but $2 is dated now!
    cp -p $3 "$3.dir/$2" 
    $RAR a "$1" "$2" >/dev/null
    cd $pwd
    rm -rf $3.dir
}

mcrarfs_copyout ()
{
    $UNRAR p -c- -inul "$1" "$2" > $3 2>/dev/null
}

mcrarfs_mkdir ()
{
# preserve pwd. It is clean, but is it necessary?
    pwd=`pwd`
# Create a directory and create in it a tmp directory with the good name     
    dir=tmpdir.${RANDOM}
    mkdir $dir
    cd $dir
    mkdir -p "$2"  
# rar cannot create an empty directory    
    touch "$2"/.rarfs
    $RAR a -r "$1" "$2" &>/dev/null
    $RAR d "$1" "$2"/.rarfs &>/dev/null
    cd $pwd
    rm -rf $dir
}

mcrarfs_rm ()
{
    $RAR d "$1" "$2" &>/dev/null
}

umask 077

# uncomment this line for debugging
#echo "`date +%T` ${0##*/} $1 $2 to=$3 tmp=$4" >>/tmp/${0##*/}.log
case "$1" in
  list)    mcrarfs_list    "$2"; exit 0;;
  rm)      mcrarfs_rm      "$2" "$3" ; exit 0;;
  rmdir)   mcrarfs_rm      "$2" "$3" ; exit 0;;
  mkdir)   mcrarfs_mkdir   "$2" "$3" ; exit 0;;
  copyin)  mcrarfs_copyin  "$2" "$3" $4; exit 0;;
  copyout) mcrarfs_copyout "$2" "$3" $4; exit 0;;
esac
exit 1
