#!/bin/sh
#
#   docker_build_tests.sh - Tests the build process on various distributions with docker
#
#   Copyright (c) 2024 Efthymios Kritikos
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
set -eu

PROJDIRNAME=$(basename $(realpath "$(dirname "$0")"/..))
cd $(realpath "$(dirname "$0")"/../..)

FAILED=0

do_test(){
	case "$1" in
		"debian:stable"|"debian:latest")
			SYSTEM_UPDATE="apt-get update ;apt-get -y install make bin86 xxd verilator g++ libz-dev"
			;;
		"ubuntu:latest")
			SYSTEM_UPDATE="apt-get update ;apt-get -y install make bin86 xxd verilator g++ libz-dev libfindbin-libs-perl"
			;;
		"fedora:latest")
			SYSTEM_UPDATE="dnf install -y make verilator dev86 g++ zlib-devel xxd"
			;;
		"archlinux:latest")
			SYSTEM_UPDATE="pacman --noconfirm -Sy make verilator xxd bin86 gcc python"
			;;
	esac
	if tar c "$PROJDIRNAME" | docker run -i "$1" bash -c 'set -eu;tar x ;'"$SYSTEM_UPDATE"'; cd 9086; make mrproper;  if [ "$(make -j boot_code/gnome_sort.run| tail -n5|head -n 1)" = "06 09 17 18 1F 21 33 37 3A 3F 44 4F 51 51 54 5D 8B 99 A5 AE DB DF E9 EE " ];then echo pass;else echo failed check; exit 1;fi ' > /dev/null 2>/dev/null
	then
		return 0
	else
		return 1
	fi
}

# ubuntu:latest has a version of verilator that is too old.
for i in debian:stable debian:latest fedora:latest archlinux:latest
do
	printf 'Testing with docker image %s \t:   ' "$i" |expand -t 44
	if ! do_test "$i"
	then
		FAILED=1
		printf '\e[1;31mFailed\e[0m\n'
	else
		printf '\e[1;32mPassed\e[0m\n'
	fi
done

if [ "$FAILED" = 1 ]
then
	exit 1
fi
