# vim: ft=zsh noet
if [[ $1 == info ]]; then
	fsb_infer_gentoo_settings

	if ! (($+STAGE_GENTOO_TARBALL_URL)); then
		typeset -g STAGE_GENTOO_TARBALL_URL
		local txt relative prefix
		txt=$FSB_GENTOO_MIRROR/releases/$STAGE_GENTOO_ARCH/autobuilds/$STAGE_GENTOO_NAME.txt
		relative=$(wget -qO - $txt | grep -o '^[^# ]\+')
		(( $pipestatus[1] )) && die "could not fetch $txt"
		[[ -z "$relative" ]] && die "no filename found in $txt"
		prefix=$txt:h
		STAGE_GENTOO_TARBALL_URL=$prefix/$relative
	fi

	FSB_INFO_DIR=$FSB_BUILD_DIR/${${STAGE_GENTOO_TARBALL_URL:t}%.tar.*}
	return
elif [[ $1 != build ]]; then
	die "unimplemented action: $*"
fi

local tarball down_dir
down_dir=$FSB_DOWNLOADS_DIR/$STAGE_GENTOO_NAME
mkdir -p $down_dir || die "Could not create directory for downloads: $down_dir"
tarball="$( fsb_download_gentoo_stage $STAGE_GENTOO_TARBALL_URL $down_dir )" || die "Could not fetch gentoo stage"
tar -xpf $tarball -C $build_dir || die "failed to extract $tarball"