#!/usr/bin/env bash
# This script uploads files from the given directory to aws S3
#
# required commands: aws
#

function usage {
    cat <<EOF
EOF
    exit 3
}

while getopts ":s:t:n:h" opt; do
  case ${opt} in
    s )
      source_dir=$OPTARG
      ;;
    t )
      target_path=$OPTARG
      ;;
    n )
      num_threads=$OPTARG
      ;;
    h )
      usage
      ;;
    \? )
      echo "Wrong arg: -$OPTARG" 1>&2
      echo "Type -h for help" 1>&2
      exit 4
      ;;
    : )
      echo "Arg -$OPTARG requires value" 1>&2
      echo "Type -h for help" 1>&2
      exit 4
      ;;
  esac
done

set -e
set -o pipefail

if [ -z "$source_dir" -o ! -d "$source_dir" ] ; then
      echo "Option -s is required and should contain existing local dir" 1>&2
      echo "Type -h for help" 1>&2
      exit 4
fi
if [ -z "$target_path" ] ; then
      echo "Option -t is required and should represent s3 destination path" 1>&2
      echo "Type -h for help" 1>&2
      exit 4
fi
if [[ $target_path != *\/ ]] ; then
      echo "Option -t is should ends with slash /" 1>&2
      exit 4
fi
if [[ $target_path != s3:\/\/* ]] ; then
      echo "Option -t is should starts with s3://" 1>&2
      exit 4
fi

# this script dir
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

echo "Source: $source_dir"
echo "Target: $target_path"
num_threads=${num_threads:-20}

(
cd $source_dir &&
find . -type f -print | sed 's/^\.\///' | xargs --max-procs=${num_threads} -I FILE bash -c "${DIR}/xargs_wrapper.sh aws s3 cp FILE ${target_path}FILE"
)
