#!/bin/bash

export MASTER_CLIENT=puzzler
export MASTER_STRESS=$MASTER_CLIENT:/home/teapot/stress
export MASTER_SERVER=magneto
export MASTER_HOSTS=magneto2    # We use magneto just for replication, while the stress client connects to magneto2
export MASTER_PORT=12398
export MASTER_SSD_DRIVES=$SSD_DRIVES
export SLAVE_CLIENT=riddler
export SLAVE_STRESS=$SLAVE_CLIENT:/home/teapot/stress
export SLAVE_SERVER=electro
export SLAVE_HOSTS=electro2     # We use electro just for replication, while the stress client connects to electro2
export SLAVE_SSD_DRIVES=$SSD_DRIVES

if [ $DATABASE == "rethinkdb" ]; then
    scp ../../build/release/rethinkdb $MASTER_SERVER:/tmp/rethinkdb
    ssh $MASTER_SERVER /tmp/rethinkdb create $MASTER_SSD_DRIVES --force
    scp ../../build/release/rethinkdb $SLAVE_SERVER:/tmp/rethinkdb
    ssh $SLAVE_SERVER /tmp/rethinkdb create $SLAVE_SSD_DRIVES --force
fi

scp $MASTER_STRESS $SLAVE_STRESS

# Store keys in temporary file.
export MASTER_TMP_KEY_FILE="$(ssh $MASTER_CLIENT mktemp)"
export SLAVE_TMP_KEY_FILE="$(ssh $SLAVE_CLIENT mktemp)"

export -p > "$BENCH_DIR/environment"

# Initialize database with a certain number of keys
DB_SIZE=50000000i
if [ $DATABASE == "rethinkdb" ]; then
    # Insert a number of keys on the master
    # TODO: This assumes that we are running on the master...
    # TODO: Should be bring up the slave now and replicate while inserting instead of when we startup master and slave later?
    ./dbench                                                                                        \
        -f -d "/tmp/replication_setup_out" -H $SERVER_HOSTS            \
        {server}rethinkdb:"-c 12 -m 32768 $MASTER_SSD_DRIVES"                                              \
        {client}stress[$STRESS_CLIENT]:"-c $CANONICAL_CLIENTS -d $DB_SIZE -w 0/0/1/0 -o $MASTER_TMP_KEY_FILE"     \
        iostat:1 vmstat:1 rdbstat:1 
                
    # Copy the keys file over to the slave's client
    scp $MASTER_CLIENT:$MASTER_TMP_KEY_FILE $SLAVE_CLIENT:$SLAVE_TMP_KEY_FILE
fi

