#!/bin/bash -e

function print_help () {
    echo "Usage: $0 MEMGRAPH_EXE MG_CLIENT_EXE"
    echo "Build example snapshots using the compiled memgraph."
}

if [[ $# -ne 2 ]]; then
  print_help
  exit 1
fi

memgraph_exe="$1"
if [[ ! -x ${memgraph_exe} ]]; then
  echo "Expected memgraph executable at '${memgraph_exe}'"
  exit 1
fi
mg_client_exe="$2"
if [[ ! -x ${mg_client_exe} ]]; then
  echo "Expected mg_client executable at '${mg_client_exe}'"
  exit 1
fi

script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
build_dir="build"
query="populate.cyp"

cd $script_dir

if [ -d "$build_dir" ]; then
  rm -rf "$build_dir"
fi

mkdir "$build_dir"

for dir in queries/*/
do
  cd $script_dir # position to script execution dir

  dir=${dir%*/}
  example=${dir#*/}

  # create snapshots directory for each example
  snapshots_dir="$build_dir/$example"
  mkdir -p "$snapshots_dir"

  # run memgraph with durability_directory pointing
  # to examples snapshots_dir
  ${memgraph_exe} --data-directory "$script_dir/$snapshots_dir/" \
                  --storage-snapshot-on-exit \
                  --storage-properties-on-edges &
  memgraph_pid=$!
  sleep 2 # wait for memgraph to start

  # create data using mg_client
  set +e
  ${mg_client_exe} --use-ssl=false < "$script_dir/$dir/$query"
  code=$?
  set -e

  if [ $code -eq 0 ]; then
    # terminate memgraph
    kill $memgraph_pid

    # wait for memgraph to terminate
    wait $memgraph_pid
  else
    # kill memgraph
    kill -9 $memgraph_pid

    # abort
    exit $code
  fi
done
