#!/bin/bash

set -ex

if test $(id -u) != 0 ; then
    SUDO=sudo
fi

$SUDO apt install -y git curl

#
# The discourse_docker commit hash is known to work with the version
#
(
    echo test_passed v2.8.0 faa7b961bbd3f7426927a8188770e190c4d2e77a
    echo old         v2.7.0 faa7b961bbd3f7426927a8188770e190c4d2e77a
    echo old         v2.6.7 80780c73687bfb082d69cba7cd225294b0aa67e9
) | while read OLD VERSION COMMIT ; do
    if ! test -d $VERSION ; then
	git clone https://github.com/discourse/discourse_docker $VERSION
    else
	git fetch
	docker rm -f app$VERSION || true
	$SUDO rm -fr $VERSION/shared
    fi
    git -C $VERSION checkout $COMMIT
    (
	cd $VERSION
	sed -e "s|SHARED|$(pwd)|" < ../app.yml > containers/app$VERSION.yml
	if test $OLD = old ; then
	    cat ../app-checkout.yml >> containers/app$VERSION.yml
	fi
	sed -e "s|VERSION|$VERSION|" -i containers/app$VERSION.yml
	if ! ./launcher rebuild app$VERSION --skip-prereqs >& ../$VERSION.log ; then
	    cat ../$VERSION.log
	    exit 1
	fi
	docker exec app$VERSION rake 'api_key:create_master[TESTKEY]' | tee apikey
	pass='BefShnygs33SwowCifViwag' ; ( echo api@example.com ; echo $pass ; echo $pass ; echo ) | docker exec -i app$VERSION rake 'admin:create'
	docker inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" app$VERSION | tee ip
    ) < /dev/null
    test $(curl --silent -X GET http://$(cat $VERSION/ip)/admin/backups -H "Accept: application/json" -H "Api-Key: $(cat $VERSION/apikey)" -H "Api-Username: api" -o /dev/null -w "%{http_code}") = 200
done
