#! /bin/sh
#
# Written by Ralf Hoffmann <ralf@boomerangsworld.de>
# uxpk 0.9.0
#
# (C) 2006 Ralf Hoffmann <ralf@boomerangsworld.de>
# May be distributed under the terms of the GNU General
# Public License V2 or higher
#
# XPK handler (http://www.jormas.com/~vesuri/xpk)
#
# Note: copyout uses xUp to uncompress the file. It requires
#       a temp directory to store a copy of the original file
#       because xUp replaces it with the uncompressed version
#       xType would be much better but unfortunatly doesn't work
#       correctly for some files
#
# The draft of XPK states that it's possible to use archives
# but the current implementation only works on files. Since extfs
# represents a virtual directory I output two entries plus a stat
# file. The two entries are of the same content but one has a fixed
# name (CONTENT) and the other uses the file name itself.

XPKCAT=xType
XPKDIR=xDir
XPKUNCOMPRESS=xUp

AWK=gawk

extfs_xpk_list ()
{
  if test -f "$1"; then
    t=$(ls -l "$1" | $AWK '{print $6, $7, $8}')
    name=$(basename "$1")
    $XPKDIR "$1" | $AWK -v time="$t" -v name="$name" \
                   '{ if ( FNR == 3 && NF >= 5 ) {
                        "id -nu" | getline uid;
                        "id -ng" | getline gid;
                        printf "-r-------- 1 %-8s %-8s %-8d %s %s\n",
                               uid, gid, $1, time, name;
                        printf "-r-------- 1 %-8s %-8s %-8d %s %s\n",
                               uid, gid, $1, time, "CONTENT";
                        printf "-r-------- 1 %-8s %-8s %-8d %s %s\n",
                               uid, gid, 0, time, "STAT";
                      }
                    }'
  fi
}

extfs_xpk_copyout ()
{
    name=$(basename "$1")
    if test "$2" = "$name" -o "$2" = "CONTENT"; then
        # This can be used if xType works correctly again
        # $XPKCAT "$1" > "$3"
        
        TMPDIR=`mktemp -u "${MC_TMPDIR:-/tmp}/extfstmpdir-uxpk.XXXXXX"` || exit 1
        trap 'if test -n "$TMPDIR"; then rm -rf "$TMPDIR"; fi; exit 0' 1 2 3 4 15
        mkdir -m 0700 "$TMPDIR" || exit 1
        cp "$1" "$TMPDIR"
        cd "$TMPDIR" && $XPKUNCOMPRESS "$name" >/dev/null && cat "$name" > "$3"
        rm -rf "$TMPDIR"
        trap 1 2 3 4 15
    elif test "$2" = "STAT"; then
        $XPKDIR "$1" > "$3"
    fi
}

# override any locale for dates
LC_ALL=C
export LC_ALL

umask 077

case "$1" in
    list)
        extfs_xpk_list "$2"
        ;;
    copyout)
        shift
        extfs_xpk_copyout "$@"
        ;;
    *)
        echo "extfs_xpk: unknown command: \"$1\"." 1>&2
        exit 1
        ;;
esac

exit 0
