#!/bin/bash

#
# ci_download_cockroachdb: fetches the appropriate CockroachDB binary tarball
# based on the currently running operating system, unpacks it, and creates a
# copy called "cockroach", all in the current directory.
#

set -o pipefail
set -o xtrace
set -o errexit

SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
ARG0="$(basename "${BASH_SOURCE[0]}")"

# If you change this, you must also update the md5sums below
CIDL_VERSION="$(cat "$SOURCE_DIR/cockroachdb_version")"
source "$SOURCE_DIR/cockroachdb_checksums"

TARGET_DIR="out"
# Location where intermediate artifacts are downloaded / unpacked.
DOWNLOAD_DIR="$TARGET_DIR/downloads"
# Location where the final cockroachdb directory should end up.
DEST_DIR="./$TARGET_DIR/cockroachdb"

# Official (or unofficial) download sites
CIDL_URL_COCKROACH="https://binaries.cockroachdb.com"
CIDL_URL_ILLUMOS="https://illumos.org/downloads"

function main
{
	#
	# Process command-line arguments. We generally don't expect any, but
	# we allow callers to specify a value to override OSTYPE, just for
	# testing.
	#
	if [[ $# != 0 ]]; then
		CIDL_OS="$1"
		shift
	else
		CIDL_OS="$OSTYPE"
	fi

	if [[ $# != 0 ]]; then
		echo "unexpected arguments" >&2
		exit 2
	fi

	# Configure this program
	configure_os "$CIDL_OS"
	CIDL_URL="$CIDL_URL_BASE/$TARBALL_FILENAME"

	# Download the file.
	echo "URL: $CIDL_URL"
	echo "Local file: $TARBALL_FILE"

	mkdir -p "$DOWNLOAD_DIR"
	mkdir -p "$DEST_DIR"

	local DO_DOWNLOAD="true"
	if [[ -f "$TARBALL_FILE" ]]; then
		# If the file exists with a valid checksum, we can skip downloading.
		calculated_md5="$($CIDL_MD5FUNC "$TARBALL_FILE")" || \
				fail "failed to calculate md5sum"
		if [[ "$calculated_md5" == "$CIDL_MD5" ]]; then
			DO_DOWNLOAD="false"
		fi
	fi

	if [ "$DO_DOWNLOAD" == "true" ]; then
		echo "Downloading..."
		do_download_curl "$CIDL_URL" "$TARBALL_FILE" || \
				fail "failed to download file"

		# Verify the md5sum.
		calculated_md5="$($CIDL_MD5FUNC "$TARBALL_FILE")" || \
				fail "failed to calculate md5sum"
		if [[ "$calculated_md5" != "$CIDL_MD5" ]]; then
			fail "md5sum mismatch \
					(expected $CIDL_MD5, found $calculated_md5)"
		fi
	fi

	# Unpack the tarball.
	do_untar "$TARBALL_FILE"

	# Copy the "cockroach" binary to the right spot.
	$CIDL_ASSEMBLE

	# Run the binary as a sanity-check.
	"$DEST_DIR/bin/cockroach" version
}

function fail
{
	echo "$ARG0: $*" >&2
	exit 1
}

function configure_os
{
	echo "current directory: $PWD"
	echo "configuring based on OS: \"$1\""
	case "$1" in
		darwin*)
			CIDL_BUILD="darwin-10.9-amd64"
			CIDL_SUFFIX="tgz"
			CIDL_MD5="$CIDL_MD5_DARWIN"
			CIDL_MD5FUNC="do_md5"
			CIDL_URL_BASE="$CIDL_URL_COCKROACH"
			CIDL_ASSEMBLE="do_assemble_official"
			;;
		linux-gnu*)
			CIDL_BUILD="linux-amd64"
			CIDL_SUFFIX="tgz"
			CIDL_MD5="$CIDL_MD5_LINUX"
			CIDL_MD5FUNC="do_md5sum"
			CIDL_URL_BASE="$CIDL_URL_COCKROACH"
			CIDL_ASSEMBLE="do_assemble_official"
			;;
		solaris*)
			CIDL_BUILD="illumos"
			CIDL_SUFFIX="tar.gz"
			CIDL_MD5="$CIDL_MD5_ILLUMOS"
			CIDL_MD5FUNC="do_md5sum"
			CIDL_URL_BASE="$CIDL_URL_ILLUMOS"
			CIDL_ASSEMBLE="do_assemble_illumos"
			;;
		*)
			fail "unsupported OS: $1"
			;;
	esac

	TARBALL_DIRNAME="cockroach-$CIDL_VERSION.$CIDL_BUILD"
	TARBALL_FILENAME="$TARBALL_DIRNAME.$CIDL_SUFFIX"

	TARBALL_FILE="$DOWNLOAD_DIR/$TARBALL_FILENAME"
	TARBALL_DIR="$DOWNLOAD_DIR/$TARBALL_DIRNAME"
}

function do_download_curl
{
	curl --silent --show-error --fail --location --output "$2" "$1"
}

function do_md5
{
	md5 < "$1"
}

function do_md5sum
{
	md5sum < "$1" | awk '{print $1}'
}

function do_untar
{
	tar xzf "$1" -C "$DOWNLOAD_DIR"
}

#
# "Assembling" here is taking unpacked tarball and putting together a directory
# structure that's common for all platforms. This allows consumers (i.e., CI)
# to assume the same directory structure for all platforms. This is
# platform-specific because on illumos, the tarball itself has a different
# structure than the official release tarballs and the `cockroach` binary has
# dynamic library dependencies.
#

function do_assemble_official
{
	mkdir -p "$DEST_DIR/bin"
	cp "$TARBALL_DIR/cockroach" "$DEST_DIR/bin"
}

function do_assemble_illumos
{
	rm -r "$DEST_DIR" || true
	cp -r "$DOWNLOAD_DIR/cockroach-$CIDL_VERSION" "$DEST_DIR"
}

main "$@"
