#!/usr/bin/env bash

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0.  If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright 1997 - July 2008 CWI, August 2008 - 2016 MonetDB B.V.

# Make a clone from a local database on a remote server.
# usage: monetdbbincopy <dbname> <passphrase> <host-list> 
# copies <dbname> to <host-list> 
# The passphrase should be sent as well for remote servers
# We presume monetdb, mclient, mnc are in PATH!
#
# If you need anything special (such as a port number) on the local or
# remote host to be passed onto monetdb, you can set the
# MONETDB_EXTRA_OPTS and RMONETDB_EXTRA_OPTS variables in the
# environment.

dbname=$1
passphrase=$2
shift 2 
hostlist=$*

if [[ -z ${dbname} || -z ${passphrase} ]] ; then
	echo "usage: monetdbbincopy <dbname> <passphrase> <host-list>"
	exit 1
fi

# take the local database down
# we don't care if the database is already locked
monetdb -q ${MONETDB_EXTRA_OPTS} lock $dbname 
# and if it's already stopped it's fine too
monetdb -q ${MONETDB_EXTRA_OPTS} stop $dbname
lpath=$(monetdb ${MONETDB_EXTRA_OPTS} status -l $dbname | \
	grep "location:" | cut -d: -f2)
# if we have no lpath, $dbname probably doesn't exist
[[ -z ${lpath} ]] && exit 1

for host in ${hostlist} ; do
	echo "$(date +%D:%H:%M): start the copy to ${host}"
	# skip doing anything if creation fails
	monetdb -q ${RMONETDB_EXTRA_OPTS} -h$host -P$passphrase create $dbname || continue
	rpath=$(monetdb ${RMONETDB_EXTRA_OPTS} -h$host -P$passphrase status -l $dbname | \
		grep "location:" | cut -d: -f2)
#	ssh -n $host "mnc -l -B $host 54321 | tar -C $rpath -jxf -" &
#	there=$!
#	sleep 1
#	tar -C ${lpath} --exclude=.mapi.sock -jcf - . | mnc -B $host 54321
#	wait $there
	tar -C ${lpath} --exclude=.mapi.sock -cf - . | xz -0 -c - | \
		ssh $host "xzcat - | tar -C $rpath -xf -"
	monetdb -q ${RMONETDB_EXTRA_OPTS} -h$host -P$passphrase release $dbname
done
echo "$(date +%D:%H:%M): done"
monetdb -q ${MONETDB_EXTRA_OPTS} release $dbname
