#!/bin/bash

set -ex

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

$SUDO apt install -y git curl

VERSION_RESTRICTION=${1:-none}

#
# The discourse_docker commit hash is known to work with the version
#
(
    echo test_passed v2.8.0 4f29decec9238444b2c5b3a5b01788fe1a182f78
    echo old         v2.7.8 4f29decec9238444b2c5b3a5b01788fe1a182f78
) | while read OLD VERSION COMMIT ; do
    if test $VERSION_RESTRICTION != none -a $VERSION_RESTRICTION != $VERSION ; then
	continue
    fi
    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="${API_PASSWORD:-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
