#!/bin/sh
#v10.1.2
globalconf="${workdir}/cbsd.conf";
MYARG=""
MYOPTARG="ver arch target_arch basename name stable dstdir distribution"
MYDESC="Create default FreeBSD distribution in .txz files"
ADDHELP="ver=head for current.\n\
stable=1 for RELENG_X\n\
dstdir= for alternative install path in root dir, default - $workdir/tmp\n\
distribution= \"base kernel ports src\"\n\
name= name of the kernel\n"

set -e
. ${globalconf}
set +e

. ${subr}
readconf buildworld.conf
. ${workdir}/universe.subr
init $*

over="${ver}"
oarch="${arch}"

# By default ver=current version
. ${buildconf}

init_base()
{
	exclude_files=""

	init_basedir

	exclude_files_lib32="/libexec/ld-elf32.so.1|\
/usr/bin/ldd32|\
/usr/lib32/.*|\
/usr/libexec/ld-elf32.so.1"

	exclude_files_rescue="/rescue/.*"

	exclude_files="^${BASE_DIR}(\
${exclude_files_lib32}|\
${exclude_files_rescue}|\
)"

	SRC_DIR="${BASE_DIR}"
}

init_ports()
{
	SRC_DIR="/usr/ports"
}

init_kernel()
{
	init_kerneldir
	SRC_DIR="${KERNEL_DIR}"
}

init_src()
{
	init_srcdir
}


## MAIN
if [ -n "${dstdir}" ]; then
	DST_DIR="${dstdir}"
else
	DST_DIR="${tmpdir}"
fi

init_target_arch
[ ! -d "${DST_DIR}" ] && /bin/mkdir -p ${DST_DIR}

if [ -z "${distribution}" ]; then
	DISTRIBUTION="base kernel"
else
	DISTRIBUTION="${distribution}"
fi

#set -x xtrace

for i in ${DISTRIBUTION}; do
	init_${i}

	if [ ! -d "${SRC_DIR}" ]; then
		${ECHO} "${MAGENTA}No such source dir for ${i}: ${GREEN}${SRC_DIR}${NORMAL}"
		continue
	fi

	${ECHO} "${MAGENTA}WIP: ${i}, source: ${GREEN}${SRC_DIR}${NORMAL}"
	cd ${SRC_DIR}

	if [ -n "${name}" ]; then
		dstname="${i}-${name}.txz"
	else
		dstname="${i}.txz"
	fi

	/usr/bin/tar -cJf ${DST_DIR}/${dstname} .
	${ECHO} "${MAGENTA} * ${DST_DIR}/${dstname}: ${GREEN}done${NORMAL}"
done
