#!/usr/bin/env bash

set -e
set -x

COMMAND_LOG="$(bazel info command_log)"
bazel build \
  //src/main/cpp/net/eagle0/shardok:shardok-server \
  //src/main/cpp/net/eagle0/shardok:shardok-inspector
STATUS="$?"

if [ $STATUS -eq 0 ]
then
  echo "Build succeeded!" > command_log.txt
else
  echo "Build failed. Copying command log from ${COMMAND_LOG}"
  cp "${COMMAND_LOG}" command_log.txt
  exit $STATUS
fi

echo "Removing old server files..."
/bin/rm -rf ./shardok

echo "Setting up Shardok files..."
/bin/mkdir -p ./shardok
/bin/cp -R ./bazel-bin/src/main/cpp/net/eagle0/shardok/shardok-server ./shardok/
/bin/mkdir -p ./shardok/shardok-server.runfiles/net_eagle0/src/main/
/bin/cp -R ./bazel-bin/src/main/cpp/net/eagle0/shardok/shardok-server.runfiles/net_eagle0/src/main/resources ./shardok/shardok-server.runfiles/net_eagle0/src/main/
/bin/cp -R ./bazel-bin/src/main/cpp/net/eagle0/shardok/shardok-inspector ./shardok/

echo "tar & zip shardok files..."
/bin/tar cfh - shardok | /usr/bin/pigz > ./deploy/shardok.tar.gz

echo "build_servers_shardok completed"
