#!/bin/bash
set -eo pipefail

if [[ ! -v DRONE_BRANCH ]]; then
	echo "This script overwrites ~/.ssh/id_rsa and hence should not be run outside of Drone!" >&2
	exit 1
fi

if [[ $DRONE_BRANCH == "staging" ]]; then
	# Staging is a branch used by bors for building pull requests before merging.
	# All artifacts produced in those builds should be uploaded as if they were built on the PR's base/target branch.
	COMMIT_MSG=$( git log -1 --pretty=format:%s )
	PR_NUMBER=$( echo "$COMMIT_MSG" | sed -r 's/^Merge #([0-9]+).*$/\1/' )
	branch=$( curl -s https://api.github.com/repos/rchain/rchain/pulls/$PR_NUMBER | jq -r '.base.ref' )
else
	branch=$DRONE_BRANCH
fi

# Instead of relying on DRONE_* vars, decide if this build a release by checking
# whether any tag points to HEAD. If more than one tags point to HEAD, pick the
# one that sorts last.

tag="$(git describe --exact-match --tags HEAD 2>/dev/null | sort -V | tail -1)" || true

if [[ -n $tag ]]; then
	upload_prefix=release/$tag/
else
	upload_prefix=branches/$branch/
fi

# Upload packages to build.rchain-dev.tk

(
umask 077
mkdir -p ~/.ssh
echo "$SSH_PRIVATE_KEY" | base64 -d | tr -d '\r' >~/.ssh/id_rsa
)

# We don't check host keys because artifacts are public.
rsync -avrz --delete -e "ssh -p 22 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" \
    artifacts/*.deb artifacts/*.rpm artifacts/*.tgz \
    inbound@build.rchain-dev.tk:/srv/inbound/$upload_prefix

# Upload Docker image

builtin echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin

# There's a slight race condition between tag and push. Tag is fast, but what
# can happen if some other jobs tags with latest while push is in progress?

docker tag coop.rchain/rnode:DRONE-$DRONE_BUILD_NUMBER rchain/rnode:$branch
docker push rchain/rnode:$branch

if [[ -n $tag ]]; then
	docker tag coop.rchain/rnode:DRONE-$DRONE_BUILD_NUMBER rchain/rnode:$tag
	docker push rchain/rnode:$tag
	docker tag coop.rchain/rnode:DRONE-$DRONE_BUILD_NUMBER rchain/rnode:latest
	docker push rchain/rnode:latest
fi
