#!/bin/bash

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -eu

usage() {
    echo "Usage: cylc [util] scp-transfer [OPTIONS]"
    echo ""
    echo "An scp wrapper for transferring a list of files and/or directories"
    echo "at once. The source and target scp URLs can be local or remote (scp"
    echo "can transfer files between two remote hosts). Passwordless ssh must"
    echo "be configured appropriately."
    echo ""
    echo "ENVIRONMENT VARIABLE INPUTS:"
    echo "\$SRCE  - list of sources (files or directories) as scp URLs."
    echo "\$DEST  - parallel list of targets as scp URLs."
    echo "The source and destination lists should be space-separated."
    echo ""
    echo "We let scp determine the validity of source and target URLs."
    echo "Target directories are created pre-copy if they don't exist."
    echo ""
    echo "Options:"
    echo " -v     - verbose: print scp stdout."
    echo " --help - print this usage message."
}

VERBOSE=false
if [[ $# -eq 1 ]]; then
    if [[ $1 = '--help' ]]; then
        usage
        exit 0
    elif [[ $1 = '-v' ]]; then
        VERBOSE=true
    else
        echo "ERROR: The only legal option is '-v'"
        exit 1
    fi
elif [[ $# -gt 1 ]]; then
    echo "ERROR: The only legal option is '-v'"
    exit 1
fi

for T in $SRCE; do
    # get destination corresponding to this target
    D=${DEST%% *}
    # remove this destination from the list of remaining destinations
    DEST=${DEST#* }

    cylc task message "Initiating file transfer from $T to $D"

    # check destination directory exists
    if [[ $D = *:* ]]; then
        # remote destination
        RMACH=${D%:*}
        RPATH=${D#*:}

        RDIR=$( dirname $RPATH )

        cylc task message "Creating remote destination directory, $RDIR"
        ssh $RMACH mkdir -p $RDIR
    else
        DIR=$( dirname $D )
        cylc task message "Creating destination directory, $DIR"
        mkdir -p $DIR
    fi

    COMMAND="scp -B -r $T $D"
    echo $COMMAND
    if $VERBOSE; then
        $COMMAND
    else
        $COMMAND > /dev/null
    fi

done
