#!/bin/bash
# Copyright (c) 2016 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

sysname="${SYSNAME:-ar}"

if [[ "$1" == "-s" ]]; then
   sysname="$2"
   shift
   shift
fi

if [[ $# -lt 2 ]]; then
   echo "Usage: $0 [-s SYSNAME] SOURCE DEST" 1>&2
   exit 1
fi

# Check for malformed arguments that can allow injection of other commands.
# E.g., dest="file:whatever\nbash sudo any-command"
outputOps="|>"
for arg in "$@"; do
   if [[ "$arg" == *[[:space:]$outputOps]* ]]; then
      echo "Illegal characters detected" 1>&2
      exit 1
   fi
done

source="$1"
dest="$2"

demux() {
   # FastCli doesn't separate normal and error output from Cli; it sends everything
   # to stdout.  This function separates that single stream into stdout and stderr.
   # Cli error messages may span multiple lines, so it's not sufficient to
   # look for the error marker '%' at the beginning of the line.
   # Here we use a simplifying assumption:
   # Until the first error marker is seen, all output is normal (stdout).
   # After the first error marker, all output is error output (stderr).
   awk '
BEGIN {
   stream = "/dev/stdout"
   rc = 0
}

# Filter out blank lines.
/^\s*$/ { next }

# Filter out the command (which is displayed for invalid input, e.g., bad URLs).
/^> copy/ { next }

# When there is an error marker, switch to stderr and remember error status.
/^% / {
   stream = "/dev/stderr"
   rc = 1
}

{
   # Remove error markers.
   sub( /^% /, "" )
   print > stream
}

END { exit rc }
   '
}

# Return an error from the pipeline if FastCli fails.
set -o pipefail

# Run the copy command as user "admin" to prevent access
# to sensitive information like /etc/shadow.
/usr/bin/sudo -u admin \
   /usr/bin/FastCli --sysname="$sysname" \
                    --privilege 15 \
                    --disable-automore \
                    --disable-aaa \
                    --command "copy $source $dest" \
                    < /dev/null \
|
demux
