#!/bin/sh
# TazPkg - Tiny autonomous zone packages manager, hg.slitaz.org/tazpkg
# pack - TazPkg module
# Create SliTaz package archive using cpio and lzma


# Connect function libraries
. /lib/libtaz.sh

# Get TazPkg working environment
. @@MODULES@@/getenv




PACKAGE="$1"
TAZPKG_PACK="$2"

cd "$PACKAGE"

if [ ! -f 'receipt' ]; then
	_ 'Receipt is missing. Please read the documentation.'
	exit 0
fi

title 'Packing package "%s"' "$PACKAGE"

# Create files.list with redirecting find output.
action 'Creating the list of files...'
cd fs
find . -type f -print >  ../files.list
find . -type l -print >> ../files.list
cd ..; sed -i s/'^.'/''/ files.list
status

action 'Creating %s of files...' "$CHECKSUM"
while read file; do
	[ -L "fs$file" ] && continue
	[ -f "fs$file" ] || continue
	case "$file" in
		/lib/modules/*/modules.*|*.pyc) continue;;
	esac
	$CHECKSUM "fs$file" | sed 's/  fs/  /'
done < files.list > $CHECKSUM
status

UNPACKED_SIZE=$(du -chs fs receipt files.list $CHECKSUM description.txt 2>/dev/null | awk 'END {print $1}')

# Build cpio archives.
action 'Compressing the FS...'
find fs | cpio -o -H newc --quiet | case "$TAZPKG_PACK" in
	gzip) gzip -9 > fs.cpio.gz ;;
	*) lzma e fs.cpio.lzma -si ;;
esac
rm -rf fs
status

PACKED_SIZE=$(du -chs fs.cpio.lzma receipt files.list $CHECKSUM description.txt 2>/dev/null | awk 'END {print $1}')

action 'Updating receipt sizes...'
sed -i s/^PACKED_SIZE.*$// receipt
sed -i s/^UNPACKED_SIZE.*$// receipt
sed -i "s/^PACKAGE=/PACKED_SIZE=\"$PACKED_SIZE\"\nUNPACKED_SIZE=\"$UNPACKED_SIZE\"\nPACKAGE=/" receipt
status

action 'Creating full cpio archive...'
find . -print | cpio -o -H newc --quiet > "../$PACKAGE.tazpkg"
status

action 'Restoring original package tree...'
case "$TAZPKG_PACK" in
	gzip) gzip -d < fs.cpio.gz;;
	*) unlzma < fs.cpio.lzma;;
esac | cpio -idm --quiet
status
rm fs.cpio.*

cd ..

footer "$(_ 'Package "%s" compressed successfully.' "$PACKAGE")"
_ 'Size: %s' "$(ls -lh "$PACKAGE.tazpkg" | awk '{print $5}')"
