# SliTaz package receipt.

PACKED_SIZE="76.0K"
UNPACKED_SIZE="80.0K"
PACKAGE="memtest64"
VERSION="6.20"
CATEGORY="base-system"
SHORT_DESC="Memory failures detection tool."
MAINTAINER="pascal.bellard@slitaz.org"
LICENSE="GPL2"
TARBALL="$PACKAGE-$VERSION.zip"
WEB_SITE="https://www.memtest.org/"	# https://github.com/memtest86plus/memtest86plus/
WGET_URL="https://memtest.org/download/v$VERSION/mt86plus_${VERSION}.binaries.zip"

BUILD_DEPENDS="xz lz4 lzsa"
BUILD_DEPENDS="xz lz4 lzsa salvador"

# What is the latest version available today?
current_version()
{
	wget -O - $WEB_SITE 2>/dev/null | \
	sed '/binaries.zip/!d;s|.*mt86plus_||;s|.binaries.zip.*||;q'
}

asm()
{
	cc -o $1.o -Wa,-a=$1.lst -c $1.S
	objcopy --only-section=.text -O binary $1.o $1.bin
}

tune_lzma()
{
	file=$1
	shift
	for i in lzma lz4x2 lzsa1x2 lzsa2x2 zx0x2 ; do
		cp $stuff/*.S $stuff/pack .
		sed "s/VERSION/$VERSION/;s|lzma1=|&nice=${1:-64},|" -i pack
		while [ -n "$2" ]; do
			sed "s|^#define PROP_$2 .*|#define PROP_$2 $3|" -i unlzma.S
			shift 2
		done
		sed -i "s|uncompress|un${i%x2}|" unpack.S
		asm bootloader
		asm unpack
		cp pack pack.bak
		./pack --build bootloader.bin unpack.bin
		PACKER=${i%x2} ./pack $file $file.${i%x2}
		if [ $(stat -c %s $file.${i%x2}) -ge $((0x101F0)) ]; then
			rm $file.${i%x2}
			cp pack.bak pack
			sed -e "s|^#define FLAT16.*// lzma case|#define FLAT16			0 // ${i%x2}|" -i unpack.S
			asm unpack
			./pack --build bootloader.bin unpack.bin
			PACKER=${i%x2} ./pack $file $file.${i%x2}
		fi
		mv unpack.lst unpack.lst.${i%x2}
		if [ "${i%x2}" != "$i" ]; then
			cp pack.bak pack
			sed -e "s|^#define DOUBLE_PACKED|#define DOUBLE_PACKED	1 // $i|" -i unpack.S
			asm unpack
			./pack --build bootloader.bin unpack.bin
			PACKER=${i%x2} ./pack $file $file.$i
			mv unpack.lst unpack.lst.$i
		fi
	done
}

# Rules to configure and make the package.
compile_rules()
{
	cc -o filter $stuff/filter.c
	mv memtest64.bin memtest64.bin.org
	dd if=memtest64.bin.org bs=512 count=1 of=memtest64.bin 2> /dev/null
	dd if=memtest64.bin.org bs=512 skip=1 | ./filter >> memtest64.bin
	tune_lzma memtest64.bin 226,mf=bt2 LC 3 PB 2

} 

# Rules to gen a SliTaz package suitable for Tazpkg.
genpkg_rules()
{
	mkdir $fs/boot
	cp $src/memtest64.bin.lzma $fs/boot/memtest64.exe
}

# Pre and post install commands for Tazpkg.
post_install()
{
	[ -s $1/boot/isolinux/isolinux.cfg ] &&
	! grep -qs 'Check 64 bits memory' $1/boot/isolinux/isolinux.cfg && sed -i \
's|LABEL md5|LABEL memtest64 mem64 ram64\
	MENU LABEL Check 64 bits memory\
	KERNEL /boot/memtest64.exe\
\n&|' $1/boot/isolinux/isolinux.cfg
	true
}
