#!/bin/bash

set -ex

dd if=/dev/zero of=/tmp/rootfs bs=1M count=50
mkfs.ext4 /tmp/rootfs

mkdir /tmp/tmp
mount /tmp/rootfs /tmp/tmp -o loop

tar xzf /tmp/alpine-minirootfs-3.14.9-aarch64.tar.gz -C /tmp/tmp

CODEDIR=${CODEDIR:-/opt/code}

cp -r  /tmp/overlay/* /tmp/tmp/

cd $CODEDIR

{{ install }}
{{ build }}

cat > /tmp/tmp/prepare.sh <<EOF
passwd root -d root
apk add -u openrc ca-certificates
exit
EOF
chroot /tmp/tmp/ /bin/sh /prepare.sh
rm /tmp/tmp/prepare.sh

umount /tmp/tmp

OUTDIR=${OUTDIR:-$CODEDIR}

mkdir -p $OUTDIR || :

cp /tmp/rootfs $OUTDIR
