FROM debian:bullseye

RUN \
	useradd -p locked -m mani && \
	apt-get -qq update && \
	apt-get -qq upgrade && \
	apt-get -qqy install curl git python-is-python3 python3-pexpect \
			     python3-distutils genisoimage qemu-system && \
	apt-get clean

RUN	git clone https://github.com/gson1703/anita.git
RUN	cd anita && python setup.py install

RUN mkdir -p -m 1777 /ccache

ARG DISK_SIZE=1G
ARG INSTALL_MEM=128M
ARG INST_IMG=http://ftp.de.netbsd.org/pub/NetBSD/NetBSD-7.1/amd64/
USER mani
RUN cd && mkdir .ccache && chown mani:mani .ccache && \
	  anita --sets kern-GENERIC,modules,base,etc,comp \
		--disk-size ${DISK_SIZE} --memory-size=${INSTALL_MEM} \
		install ${INST_IMG} && \
	  rm -rf work-*/download

ARG EXTRA_PKG=""
ARG RUNTIME_MEM=128M
ARG ORIGIN=https://review.sourcearcade.org/flashprog.git
ARG PKG_PATH=http://cdn.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/7.1/All
RUN cd && \
	PKG_PATH=$(curl -ILso /dev/null -w %{url_effective} ${PKG_PATH}) && \
	PKG_PATH=http:${PKG_PATH#http*:} && \
	anita --persist --memory-size=${RUNTIME_MEM} --run \
"echo 'ip6addrctl=YES'                          >>/etc/rc.conf && \
 echo 'ip6addrctl_policy=ipv4_prefer'           >>/etc/rc.conf && \
 echo 'dhcpcd --waitip'                          >init && \
 echo 'export PKG_PATH=${PKG_PATH}'             >>init && \
 service ip6addrctl restart && \
 . ./init && \
 pkg_add gmake git-base ccache pkg-config meson \
         pciutils libusb1 libusb-compat libjaylink \
         ${EXTRA_PKG} && \
 git config --global --add http.sslVerify false && \
 git clone ${ORIGIN} flashprog" \
		boot ${INST_IMG}

RUN cd && dd if=/dev/zero bs=1M count=64 of=cache.img && \
	  anita --vmm-args \
			'-drive file=cache.img,index=1,media=disk,format=raw' \
		--persist \
		--memory-size=${RUNTIME_MEM} --run \
"if [ \$(uname -m) = i386 -o \$(uname -m) = amd64 ]; then \
     bdev=wd1d; \
 else \
     bdev=wd1c; \
 fi; \
 newfs -I \${bdev} && \
 mkdir .ccache && \
 mount /dev/\${bdev} .ccache && \
 ccache -M 60M && \
 umount .ccache && \
 echo 'manitest() {'                            >>init && \
 echo '    fsck -y -t ffs /dev/'\${bdev}        >>init && \
 echo '    mount /dev/'\${bdev}' ~/.ccache'     >>init && \
 echo '    (cd ~/flashprog && eval \" \$*\")'    >>init && \
 echo '    ret=\$?'                             >>init && \
 echo '    umount ~/.ccache'                    >>init && \
 echo '    return \$ret'                        >>init && \
 echo '}'                                       >>init" \
		boot ${INST_IMG} && \
	  gzip cache.img

COPY anita-wrapper.sh /home/mani/mani-wrapper.sh
ENV INST_IMG ${INST_IMG}
ENV MEM_SIZE ${RUNTIME_MEM}
ENTRYPOINT ["/bin/sh", "/home/mani/mani-wrapper.sh"]
