#!/bin/bash
# packs host-tools to dl/tools-DATE.tar.xz in ~6min

miniconfig() {
local i
for i in "$@"; do echo "$i=y"; done
cat << EOF
FREETZ_USER_LEVEL_EXPERT=y
FREETZ_HOSTTOOLS_DOWNLOAD=n
FREETZ_TOOLCHAIN_CCACHE=n
FREETZ_JLEVEL=9
EOF
}

SKIP="config yf"
FILE="tools-$(date '+%Y-%m-%d')"
OUTP="dl/$FILE.tar.xz"
[ -s "$OUTP" ] && echo "File $OUTP exists" && exit 1

TOOLS="$(ls tools/make/*/*.mk | sed 's!.*/!!;s/.mk$//g')"
LOCAL="$(sed -n 's/^TOOLS_BUILD_LOCAL.=//p' tools/make/Makefile.in)"
BUILD="$(echo "$TOOLS" | grep -vE "^$(echo $LOCAL | sed 's/ /|/g')$")"

TOOL_CONF=tools/config/conf
make distclean
rm -rf dl 2>/dev/null
ln -sf ~/.freetz-dl dl
mkdir -p dl
make $TOOL_CONF
miniconfig > .config
$TOOL_CONF --olddefconfig config/Config.in
cp -a .config "$FILE.conf"
time for x in $BUILD; do make $x; done 2>&1 | tee "$FILE.make"  # 4min
for x in $LOCAL; do [ "$x" != "tools-host" ] && make $x-distclean; done
time sed -n 's,^/,tools/,p' tools/.gitignore | grep -vE "/(${SKIP// /|})$" | tar cvf - -T - | xz -9 - > "$OUTP"  # 1min
du -h "$OUTP"
sha256sum "$OUTP"
ln -f "$OUTP"
echo "Created ${OUTP##*/}"