#!/bin/zsh
DO=$0
main() {
	args build_dir fstab arch! sabotage_url
	clone-depend sabotage-checkout sabotage_url:
	eval $(getvars)

	local sabotage_conf
	sabotage_conf=(
	'## set your arch, or try `uname -m`'
	'export A='${(q)arch}
	'export ARCH=$A'
	''
	'## set the compiler environment'
	'export CC=gcc'
	'export HOSTCC=gcc'
	''
	'## set your core count for faster builds, this is passed as -jXXX to make'
	'## stage0 builds in less than 2minutes using -j9 on an AMD 8core'
	'export MAKE_THREADS='$(grep $'^processor[ \t]*:' /proc/cpuinfo | wc -l)
	': ${MAKE_THREADS:=1}'
	''
	'# internal paths'
	'# you should leave these all as-is, this is the intended way.'
	'# K is the directory where patches and configs are kept'
	'# C is the directory to place the downloaded tarballs'
	'# S is the directory to extract tarballs and place sources for building stage0'
	'# R is the directory underwhich the new filesystem will be created'
	'# LOGPATH is the directory to place logfiles of builds'
	''
	'# needed to inherit $PWD from toplevel buildscript'
	'[ -z "$H" ] && H="$PWD"'
	''
	'## set path to builddir (where you want your chroot).'
	'export SABOTAGE_BUILDDIR=$(realpath "$H/..")'
	''
	'export K="$H"/KEEP'
	'#export C="$H"/tarballs'
	'export C='${(q)DO:h:a}/downloads/sabotage-tarballs
	'export R="$SABOTAGE_BUILDDIR"'
	'export S="$R"/src'
	'export LOGPATH="$S"/logs'
	''
	'export BUTCH_BUILD_TEMPLATE="$K"/butch_build_template.txt'
	'export BUTCH_DOWNLOAD_TEMPLATE="$K"/butch_download_template.txt'
	''
	'# this is needed so packages can detect from which stage they'\''re called'
	'export STAGE=0'
	)
	printf '%s\n' $sabotage_conf >$build_dir/src/config \
		|| die "failed to set up config"

	printf '%s\n' '#!/bin/sh' 'exec true' \
		>$build_dir/src/utils/update-chroot.sh || die

	(cd $build_dir/src && ./build-stage0) \
		|| die "failed to build stage0"

	rm -rf $build_dir/src/{build,logs} \
		|| die "failed to remove temporary files"
}
. ./common.zsh
# vim: fileencoding=utf8 ft=zsh noet sw=4 ts=4 sts=4