#!/bin/mksh
# $MirOS: src/scripts/tarsets,v 1.12 2009/09/15 15:42:48 tg Exp $
#-
# Copyright (c) 2004, 2006, 2007, 2009
#	Thorsten Glaser <tg@mirbsd.org>
#
# Provided that these terms and disclaimer and all copyright notices
# are retained or reproduced in an accompanying document, permission
# is granted to deal in this work without restriction, including un-
# limited rights to use, publicly perform, distribute, sell, modify,
# merge, give away, or sublicence.
#
# This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
# the utmost extent permitted by applicable law, neither express nor
# implied; without malicious intent or gross negligence. In no event
# may a licensor, author or contributor be held liable for indirect,
# direct, other damage, loss, or other issues arising in any way out
# of dealing in the work, even if advised of the possibility of such
# damage or existence of a defect, except proven that it results out
# of said person's immediate fault when using the work as intended.

me=${0##*/}
cwd=$(realpath .)
arch=${MACHINE:-$(uname -m)}

function tarsets {
	set=${1##*/}
	[[ -e $cwd/$set/mi && -e $cwd/$set/md.$arch ]] || return 0
	cat "$cwd/$set/mi" "$cwd/$set/md.$arch" 2>/dev/null | sort $2
}

function usage {
	print -u2 "Syntax: $me [check | make <release>]"
	exit 1
}

if [[ -z $DESTDIR ]]; then
	print "Must set DESTDIR before calling ${0##*/}!"
	exit 1
fi

if [[ $doz = [Nn]?([Oo]) ]]; then
	compressor=cat
	extension=newc
	zt=uncompressed
else
	[[ $doz = [1-9] ]] || doz=9
	compressor="gzip -n$doz"
	extension=ngz
	zt="gzip'd"
fi

case $1 {
(c*)
	T=$(mktemp /tmp/_tmp.XXXXXXXXXX) || exit 1
	trap 'rm -f $T ; exit 0' 0
	trap 'rm -f $T ; exit 1' 1 2 3 5 13 15

	for set in */mi; do
		tarsets "${set%/mi}"
	done | cat - ignfiles 2>/dev/null | sort >$T

	( cd "$DESTDIR"; find . \( -type d -o -type f -o -type l \) ) \
	    | grep -v -e '^\./snapshot' -e '^.$' | sort | diff -du $T -
	;;
(m*)
	rel=$2
	[[ -n $rel ]] || usage

	if [[ -z $RELEASEDIR ]]; then
		print -u2 "Must set RELEASEDIR before calling $me!"
		exit 1
	fi

	print "Generating $zt release tarballs for MirOS #${rel}/${arch}"

	cd "$DESTDIR"
	for set in $cwd/*/mi; do
		set=${set%/mi}
		[[ -e $set/md.$arch ]] || continue
		print -n "${set##*/}..."
		tarsets "$set" -u | \
		    sed -n 's!^\.//*!!p' | \
		    cpio -oC512 -Hsv4cpio -Mset | \
		    $compressor >"$RELEASEDIR/${set##*/}$rel.$extension"
		print done.
	done
	cd "$cwd"
	;;
(*)
	usage
	;;
}
