+remote_pool=${2%%/*}
+
+# get the backup pool from the command line or the config file if not specified
+if [[ -n $3 ]]; then
+ backup_pool=$3
+else
+ backup_pool=${backup_pool%% *} # use the first backup pool if none specified
+fi
+
+# Setup our cleanup and exit trap
+cleanup() {
+ if [[ -e "$local_list" ]]; then
+ rm -f $local_list
+ fi
+ if [[ -e "$remote_list" ]]; then
+ rm -f $remote_list
+ fi
+ $ssh $remote ls -d "$lockdir" > /dev/null 2>&1
+ if [[ $? == 0 ]]; then
+ $ssh $remote rm -rf "$lockdir"
+ fi
+}
+fatal_and_exit() {
+ echo -e 2>&1 "$1"
+ # Destroy the current backup markers from the local backup_pool and remote_pool if they exist
+ if [[ -n "$current_backup_marker" ]]; then
+ # Local backup pool current backup marker
+ $zfs list -t snapshot ${backup_pool}/${current_backup_marker} > /dev/null 2>&1
+ if [ $? == 0 ]; then
+ $zfs destroy ${backup_pool}/${current_backup_marker}
+ fi
+ # Remote pool current backup marker
+ $ssh $remote zfs list -t snapshot ${current_backup_marker} > /dev/null 2>&1
+ if [ $? == 0 ]; then
+ $ssh $remote $zfs destroy ${current_backup_marker}
+ fi
+ fi
+ # send email notification
+ if [[ -n "$2" ]]; then
+ echo -e "$1" | $mailx -s "zfs replicate on $hostname failed" "$2"
+ fi
+ # exit
+ exit 1
+}
+trap fatal_and_exit INT
+trap cleanup EXIT
+
+# Declare a function to handle the replicate operation
+replicate() {
+ zfs_send="$1"
+ zfs_recv="$zfs receive -vF -d ${backup_pool}/${remote_pool}"
+ glue="$throttle $throttle_opt"
+ if [[ $throttle_enable == 1 && -e $throttle ]]; then
+ # handle using the glue in the local and remote host case properly
+ if [[ -z "$ssh" ]]; then
+ # local host glue case
+ $zfs_send | $glue | $zfs_recv
+ else
+ # remote host glue case
+ $ssh $remote "$zfs_send | $glue" | $zfs_recv
+ fi
+ else
+ # no glue case - works for both the local and remote host cases
+ $ssh $remote $zfs_send | $zfs_recv
+ fi
+ # The return code of the zfs_send | zfs_recv operation will be returned to the caller
+}
+
+# Make sure we have valid arguments
+if [[ -z "$remote" ]] || [[ -z "$remote_fs" ]]; then
+ fatal_and_exit "Usage: $0 <hostname> <zfs filesystem>"
+fi
+
+# check for localhost
+if [[ $remote = "localhost" ]]; then
+ remote=""
+ ssh=""
+fi
+
+# Make sure the local backup pool and local receiving filesystem exist, or print some errors
+zpool list -H "$backup_pool" >/dev/null 2>&1
+if [ $? != 0 ]; then
+ fatal_and_exit "-E- The local backup pool on $hostname, '$backup_pool' doesn't seem to exist." $mailto
+fi
+zfs list "$backup_pool/$remote_pool" >/dev/null 2>&1
+if [ $? != 0 ]; then
+ echo >&2 "-I- The local filesystem for the remote pool, '$backup_pool/$remote_pool' doesn't seem to exist."
+ echo >&2 " Creating the local filesystem to receive the remote pool into: $backup_pool/$remote_pool"
+ $zfs create $backup_pool/$remote_pool
+ if [ $? != 0 ]; then
+ fatal_and_exit "-E- remote $zfs on $hostname create command failed" $mailto
+ fi
+fi