#!/bin/sh
# buildenv: set up THIS container (glacier-alpine_root, started with
# `./run_docker.sh -b Dockerfile.alpine_root`) to build packages from
# source, with local repositories:
#
#   buildenv [RECIPES]
#
#   RECIPES   a directory of NAME/ recipe dirs (default
#             /recipes/extra-src, which run_docker.sh -b mounts)
#
# It makes, once: the system (syspkg -n), the build user gbuild, a
# signing key "repokey", /srv/extra with a toolchain package made from
# Alpine's build-base (tests/mkroot; Everest has no toolchain packages
# yet), BUILD_ROOT/BUILD_USER/JOBS in /etc/glacier/glacier.conf, and
# /etc/glacier/repos.conf listing extra and extra-src. Every run packs
# RECIPES into /srv/extra-src (tests/mkgrcp), signs both indexes and
# syncs, so rerun it after editing a recipe.

set -e
recipes=${1:-/recipes/extra-src}
t=$(dirname "$(realpath "$0")")
export PATH="/app:$PATH"

[ -d "$recipes" ] || { echo "buildenv: no recipe directory $recipes" >&2; exit 1; }
[ -d /glacier/sys ] || syspkg -n
id gbuild >/dev/null 2>&1 || adduser -S -D -H gbuild
mkdir -p /srv/extra /srv/extra-src
chmod 755 /srv /srv/extra /srv/extra-src

if [ ! -f /srv/extra/toolchain-1.0.0.gpkg ]; then
	echo "Packing the toolchain (Alpine's build-base)..."
	"$t/mkroot" -o /srv/extra -r build-base -r busybox -p busybox toolchain 1.0.0 extra
fi

rm -f /srv/extra-src/*.grcp
"$t/mkgrcp" -o /srv/extra-src "$recipes"/*/

[ -f /root/repokey.sec ] ||
	gsign -G -p /etc/glacier/keys/repokey.pub -s /root/repokey.sec -c repokey
grepo -s /root/repokey.sec -r extra /srv/extra
grepo -s /root/repokey.sec -r extra-src /srv/extra-src

cat > /etc/glacier/repos.conf <<'EOR'
repos = (
	{ name = "base"; keys = [ "glacier-test" ]; },
	{ name = "extra"; url = "file:///srv/extra"; keys = [ "repokey" ]; },
	{ name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "repokey" ]; }
);
EOR
chmod 644 /etc/glacier/repos.conf

c=/etc/glacier/glacier.conf
grep -q '^BUILD_ROOT' $c || echo 'BUILD_ROOT = [ "toolchain" ];' >> $c
grep -q '^BUILD_USER' $c || echo 'BUILD_USER = "gbuild";' >> $c
grep -q '^JOBS' $c || echo "JOBS = $(nproc);" >> $c

syspkg -y
