#!/bin/bash

function printHelp() {
  >&2 echo "USAGE: $0 -s INFLUXDB_SHA -b INFLUXDB_BRANCH -v INFLUXDB_VERSION

Emits a tarball of influxdb source code and dependencies to /out,
which must be a mounted volume if you want to access the file.

If the directory /influxdb-git exists and is mounted,
that will be used as the git repository used when cloning influxdb.
"
}

if [ $# -eq 0 ]; then
  printHelp
  exit 1
fi

SHA=""
BRANCH=""
VERSION=""

while getopts hs:b:v: arg; do
  case "$arg" in
    h) printHelp; exit 1;;
    s) SHA="$OPTARG";;
    b) BRANCH="$OPTARG";;
    v) VERSION="$OPTARG";;
  esac
done

if [ -z "$SHA" ] || [ -z "$BRANCH" ] || [ -z "$VERSION" ]; then
  printHelp
  exit 1
fi

IPATH=/go/src/github.com/influxdata
mkdir -p "$IPATH" && cd "$IPATH"
if [ -d /influxdb-git ]; then
  git clone /influxdb-git "$IPATH/influxdb"
else

  git clone https://github.com/influxdata/influxdb.git
fi

cd influxdb
git checkout "$SHA"
dep ensure -vendor-only
cd ..

# Emit version metadata to appropriate files.

# Include machine-parseable metadata JSON file.
printf '{
"version": "%s",
"branch": "%s",
"sha": "%s"
}' "$VERSION" "$BRANCH" "$SHA" > "./influxdb/.metadata.json"

# Set version info for influxdb binaries.

printf 'package main

// Code generated by influxdata/releng tooling. DO NOT EDIT.

func init() {
	version = "%s"
	branch = "%s"
	commit = "%s"
}' "$VERSION" "$BRANCH" "$SHA" > "./influxdb/cmd/influxd/version.generated.go"


# influx uses just version.
printf 'package main

// Code generated by influxdata/releng tooling. DO NOT EDIT.

	func init() {
	version = "%s"
}' "$VERSION" > "./influxdb/cmd/influx/version.generated.go"

# Prebuild the man pages so that consumers of the source tarball don't have to build it themselves.
(cd /go/src/github.com/influxdata/influxdb/man && make build && gzip -9 ./*.1)

TARBALL_NAME="influxdb-src-$SHA.tar.gz"
(cd /go && tar czf "/out/$TARBALL_NAME" --exclude-vcs ./*) # --exclude-vcs is a GNU tar option.
(cd /out && md5sum "$TARBALL_NAME" > "$TARBALL_NAME.md5")
(cd /out && sha256sum "$TARBALL_NAME" > "$TARBALL_NAME.sha256")
