#!/usr/bin/env bash
#
# bdr_initial_load copies data from a running BDR instance's database to the empty
# local database that's due to be joined into the BDR group.
#
# It must exit with an error if the dump OR the load fails. The load must be
# performed in a single transaction or must use --clean to flush any local
# contents first, i.e. it must cope with being re-run if the restore is
# interrupted.
#

errlog()
{
   echo "$@" 1>&2
}

JOBS=1

i=0
argv=("$@")

PGDUMP=
PGRESTORE=

while (($i < ${#argv[*]})); do
	case "${argv[$i]}" in
	-V)
		echo "bdr_initial_load (PostgreSQL 9.4.14, BDR 1.0.3)"
		exit
	;;
	--snapshot)
		((i++)); SNAPSHOT="${argv[$i]}"
	;;
	--source)
		((i++)); SOURCE="${argv[$i]}"
	;;
	--target)
		((i++)); TARGET="${argv[$i]}"
	;;
	--tmp-directory)
		((i++)); TMPDIR="${argv[$i]}"
	;;
	--jobs)
		((i++)); JOBS="${argv[$i]}"
	;;
	--pg-dump-path)
		((i++)); PGDUMP="${argv[$i]}"
	;;
	--pg-restore-path)
		((i++)); PGRESTORE="${argv[$i]}"
	;;
	--help)
		errlog "Usage: bdr_initial_load --source <dsn> --target <dsn> [--snapshot <name>] --dir /path/to/dir [--jobs N]"
		errlog "<dsn> is a libpq conninfo string, e.g. \"host=/tmp port=5433 dbname=xxx\""
		exit 0
	;;
	*)
		errlog Unknown command-line option: ${argv[$i]}
		exit 1
	;;
	esac

	((i++))
done

if [ -z "$SOURCE" ]; then
	errlog Please specify a source DSN with '--source "port=nnn dbname=xxx"'; exit 1
fi

if [ -z "$TARGET" ]; then
	errlog Please specify a target DSN with '--target "port=nnn dbname=xxx"'; exit 1
fi

if [ -z "$TMPDIR" ]; then
	errlog Please specify a directory with '--temp-directory /path/to/dir'; exit 1
fi

if [ -z "$PGDUMP" ]; then
	errlog The path to pg_dump must be specified with '--pg-dump-path ./path/pg_dump'; exit 1
fi

if [ -z "$PGRESTORE" ]; then
	errlog The path to pg_restore must be specified with '--pg-dump-path ./path/pg_dump'; exit 1
fi

SNAP=${SNAPSHOT:+"--snapshot $SNAPSHOT"}

errlog "Dumping remote database \"$SOURCE\" with $JOBS concurrent workers to \"$TMPDIR\""
if ! "$PGDUMP" -T "bdr.bdr_nodes" -T "bdr.bdr_connections" --bdr-init-node -j $JOBS $SNAP -F d -f $TMPDIR "$SOURCE"; then
	errlog "bdr_dump of "$SOURCE" failed, aborting"
	exit 1
fi

errlog "Restoring dump to local DB \"$TARGET\" with $JOBS concurrent workers from \"$TMPDIR\""
if ! "$PGRESTORE" --exit-on-error -j $JOBS -F d -d "$TARGET" $TMPDIR; then
	errlog "pg_restore to "$TARGET" failed, aborting"
	exit 2
fi

exit 0
