#!/bin/bash
# -------------------------------------------------------------------
# Copyright (C) 2016, 2020, 2023 by Intevation GmbH
# Author(s):
# Sascha Wilde <wilde@intevation.de>

# This program is free software under the GNU GPL (>=v2)
# Read the file COPYING coming with the software for details.
# -------------------------------------------------------------------

# Copy file from remote source to remote destination without temporary
# local copy.

VERSION='0.4'
ME=`basename "$0"`
VERBOSE=0
DEBUG=0
EXTRA_SRC_OPTS=""

usage()
{
  cat <<EOF
$ME [OPTIONS] SRC DST

Copies a file from remote SRC to remote DST without storing a
(temporary) local copy.  SRC and DST are paths ins standard ssh
notation.

Options:
  -h, --help                  show this help text.
  -v, --verbose               show extra information on executed statements.
  -V, --version               show version information and exit.
  -x, --one-file-system       don't cross filesystem boundaries
      --debug                 print extra technical debug information.
EOF
}

fatal()
{
  echo >&2 "$1"
  exit 23
}

verbose()
{
  [ $VERBOSE -ne 0 ] && echo "$*"
}

debug()
{
  [ $DEBUG -ne 0 ] && echo "$*"
}

rcopy()
{
  local src="$1"
  local dst="$2"
  local src_host="${src%:*}"
  local src_path="${src##*:}"
  local src_file=`basename "$src_path"`
  local src_path=`dirname "$src_path"`
  local dst_host="${dst%:*}"
  local dst_path="${dst##*:}"
  verbose "Copying \"$src_path/$src_file\" from $src_host to \"$dst_path\" on $dst_host ..."
  ssh "$src_host" "cd \"${src_path:-./}\" && tar $EXTRA_SRC_OPTS -c $src_file" \
    | ssh "$dst_host" "tar -C '${dst_path:-./}' -xvf -"
}

### pars opts

OPTS=`getopt \
      -l help,verbose,debug,version,one-file-system \
      -o hvVx -n "$ME" -- "$@"`
[ $? -eq 0 ] || usage

eval set -- "$OPTS"

while true ; do
  case "$1" in
    --verbose|-v)
      VERBOSE=1
      shift
      ;;
    --one-file-system|-x)
      EXTRA_SRC_OPTS+="--one-file-system "
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    --version|-V)
      echo "$ME Version $VERSION"
      exit 0
      ;;
    --debug)
      DEBUG=1
      shift
      ;;
    --)
      shift
      break
      ;;
  esac
done

### main

[ $# -eq 2 ] || { usage ; exit 1 ; }
rcopy "$1" "$2"
