#!/bin/bash -e

PUBLIC=1

if [[ "$1" == "--private" ]]; then
  PUBLIC=
  shift
fi

SRC=$1
DEST=$2

if [[ -z "${SRC}" ]]; then
  echo "syntax: $0 [--private] <src> <dest>"
  exit 1
fi

if [[ -z "${DEST}" ]]; then
  echo "syntax: $0 [--private] <src> <dest>"
  exit 1
fi

if [[ "${DEST:0:5}" == "s3://" ]]; then
  acl_flag="${PUBLIC:+--acl public-read}"
  bucket=$(echo "${DEST}" | cut -d/ -f3)
  # S3 buckets with BucketOwnerEnforced error on attempts to set ACLs
  if aws s3api get-bucket-ownership-controls --bucket "${bucket}" | grep -q "BucketOwnerEnforced" 2>/dev/null; then
    acl_flag=""
  fi
  aws s3 sync --no-progress ${acl_flag} ${SRC} ${DEST}
  exit 0
fi

if [[ "${DEST:0:5}" == "gs://" ]]; then
  bucket=$(echo "${DEST}" | cut -d/ -f1-3)
  acl_flag="${PUBLIC:+--predefined-acl=publicRead}"
  # GCS buckets with UBLA enabled error on attempts to set ACLs
  # ref: https://cloud.google.com/storage/docs/uniform-bucket-level-access#enabled
  if [[ "$(gcloud storage buckets describe "${bucket}" --format="value(uniform_bucket_level_access)" 2>/dev/null)" == "True" ]]; then
    acl_flag=""
  fi
  gcloud storage rsync --recursive --cache-control="private,max-age=0" ${acl_flag} ${SRC} ${DEST}
  exit 0
fi

if [[ "${DEST:0:6}" == "oss://" ]]; then
	aliyun oss cp ${PUBLIC:+--acl public-read} -r -f --include "*" ${SRC}/ ${DEST}
  exit 0
fi

if [[ "${DEST:0:5}" == "do://" ]]; then
  DO_BUCKET=`echo "${DEST}" | cut -c 6-`
  s3cmd put "*" ${SRC}/ s3://$DO_BUCKET --recursive ${PUBLIC:+--acl-public}
  exit 0
fi

if [[ "${DEST:0:6}" == "scw://" ]]; then
  SCW_BUCKET=$(echo "${DEST}" | cut -c 7-)
  echo "--> s3cmd put ${SRC} s3://$SCW_BUCKET --recursive ${PUBLIC:+--acl-public} --progress"
  s3cmd put ${SRC} s3://$SCW_BUCKET --recursive ${PUBLIC:+--acl-public} --progress
  exit 0
fi

echo "Unsupported destination - supports s3://, gs:// and oss:// urls: ${DEST}"
exit 1
