#!/bin/bash

# This script is intended to run the tests we run at circleci,
# precisely as they are run there.
#
# to do so, it:
# o creates a directory to store local artifacts retrieved from docker
#   see TMP= below
# o runs the standard test container to retrieve a the qemu, kernel, and bios image
# o runs go test with a default set of tests (./...)
#
# NOTE: if you want more complex behavior, don't make this script more
# complex. Convert it to Go. Complex shell scripts suck.

# These docker artifacts should not persist. Place them in tmp.
# tmp is in .gitignore
# I would prefer /tmp/$$.
# Docker really doesn't like this for some reason, even when
# I map it to /out inside the container.
TMP=`pwd`/tmp
mkdir -p $TMP
chmod 777 $TMP

# The default value is amd64, but you can override it, e.g.
# UROOT_TESTARCH=arm64 bash RUNLOCAL
export UROOT_TESTARCH=${UROOT_TESTARCH:=amd64}

case $UROOT_TESTARCH in

  "amd64")
    export UROOT_QEMU="qemu-system-x86_64"
    export UROOT_QEMU_OPTS="-L $TMP/pc-bios -m 1G"
    export UROOT_KERNEL=bzImage
    export UROOT_BIOS=pc-bios
    ;;

  "arm64")
    export UROOT_QEMU=qemu-system-aarch64
    export UROOT_KERNEL=Image
    export UROOT_BIOS=""
    export UROOT_QEMU_OPTS=""
    ;;

  "arm")
    export UROOT_QEMU=qemu-system-arm
    export UROOT_KERNEL=zImage
    export UROOT_BIOS=""
    export UROOT_QEMU_OPTS='-M virt -nographic'
    export UROOT_QEMU_TIMEOUT_X=10

    ;;

  *)
    echo "$UROOT_TESTARCH is not a supported architecture (amd64, arm64, arm)"
    exit 1
    ;;

esac

# We no longer allow you to pick a kernel to run.
# Since we wish to exactly mirror what circleci does, we always use the
# kernel and qemu in the container.
# Note the docker pull only hurts a lot the first time.
# After you have run it once, further cp operations take a second or so.
# By doing it this way, we always use the latest Docker files.
CONTAINER=uroottest/test-image-${UROOT_TESTARCH}

DIR=/home/circleci

docker run $CONTAINER bash -c "echo \$UROOT_QEMU"
docker run $CONTAINER tar Ccf $DIR - $UROOT_KERNEL $UROOT_QEMU $UROOT_BIOS | tar Cxf $TMP -

ls -l $TMP

# now adjust paths and such
export UROOT_KERNEL=$TMP/$UROOT_KERNEL
export UROOT_QEMU="$TMP/$UROOT_QEMU $UROOT_QEMU_OPTS"
export UROOT_BIOS=$TMP/$UROOT_BIOS
