#!/usr/bin/env bash

set -eu

SOURCE_DIR="$PWD"
VERSION="$(cat VERSION)"

# To distinguish dev and release builds, we append "-devDATE.REVISION" to dev builds.
if [ "${DEV:-yes}" = "yes" ]; then
    REV="$(git log -n 1 --no-walk --pretty="%h")"
    VERSION="$VERSION-dev$(TZ="UTC" date "+%Y%m%d").$REV"
fi

# Make a dir for the package in distro/.
PKG_NAME="pmm-client-$VERSION-x86_64"
PKG_DIR="distro/$PKG_NAME"

rm -rf $PKG_DIR distro/bin
mkdir -p $PKG_DIR/bin distro/bin

echo "Preparing $PKG_NAME"
echo

# Default build for linux, not Darwin.
export GOOS=linux

printf "Building pmm-admin...\t\t"
echo $(git log -1 --format="%d %cd")
go build -ldflags "-X github.com/percona/pmm-client/pmm.Version=$VERSION" -o distro/bin/pmm-admin

printf "Building percona-qan-agent...\t"
cd $GOPATH/src/github.com/percona/qan-agent
echo $(git log -1 --format="%d %cd")

cd $SOURCE_DIR
go build -ldflags "-X github.com/percona/qan-agent/agent/release.VERSION=$VERSION" \
    -o distro/bin/percona-qan-agent github.com/percona/qan-agent/bin/percona-qan-agent

echo "Building percona-qan-agent-installer..."
go build -ldflags "-X github.com/percona/qan-agent/agent/release.VERSION=$VERSION" \
    -o distro/bin/percona-qan-agent-installer github.com/percona/qan-agent/bin/percona-qan-agent-installer

printf "Building node_exporter...\t"
cd $GOPATH/src/github.com/prometheus/node_exporter
make
mv ./node_exporter $SOURCE_DIR/distro/bin/node_exporter

printf "Building mysqld_exporter...\t"
cd $GOPATH/src/github.com/percona/mysqld_exporter
commit=$(git rev-parse HEAD)
branch=$(git rev-parse --abbrev-ref HEAD)
echo $(git log -1 --format="%d %cd")
importpath=github.com/percona/mysqld_exporter/vendor/github.com/prometheus/common
cd $SOURCE_DIR
go build -ldflags "-X $importpath/version.Version=$VERSION -X $importpath/version.Branch=$branch -X $importpath/version.Revision=$commit" \
    -o distro/bin/mysqld_exporter github.com/percona/mysqld_exporter

printf "Building postgres_exporter...\t"
cd $GOPATH/src/github.com/percona/postgres_exporter
make
mv ./postgres_exporter $SOURCE_DIR/distro/bin/postgres_exporter

printf "Building mongodb_exporter...\t"
cd $GOPATH/src/github.com/percona/mongodb_exporter
make
mv ./mongodb_exporter $SOURCE_DIR/distro/bin/mongodb_exporter

printf "Building proxysql_exporter...\t"
cd $GOPATH/src/github.com/percona/proxysql_exporter
make
mv ./proxysql_exporter $SOURCE_DIR/distro/bin/proxysql_exporter

# Prepare tarball dir.
cd $SOURCE_DIR
cp CHANGELOG.md VERSION LICENSE scripts/install scripts/uninstall $PKG_DIR
cp distro/bin/* $PKG_DIR/bin

cd distro
tar czf $PKG_NAME.tar.gz $PKG_NAME

echo
echo "Done with $PKG_DIR.tar.gz"
echo
