#!/usr/bin/env bash
# A simple script to upload pex dependencies to s3 and generate corresponding
# s3 urls to be used in the workspace file

pex_deps_urls="
https://pypi.python.org/packages/c4/bf/80d1cd053b1c86f6ecb23300fba3a7c572419b5edc155da0f3f104d42775/pytest-3.0.2-py2.py3-none-any.whl
https://pypi.python.org/packages/19/f2/4b71181a49a4673a12c8f5075b8744c5feb0ed9eba352dd22512d2c04d47/py-1.4.31-py2.py3-none-any.whl
https://pypi.python.org/packages/c9/1d/bd19e691fd4cfe908c76c429fe6e4436c9e83583c4414b54f6c85471954a/wheel-0.29.0.tar.gz
https://pypi.python.org/packages/d3/16/21cf5dc6974280197e42d57bf7d372380562ec69aef9bb796b5e2dbbed6e/setuptools-20.10.1.tar.gz
https://pypi.python.org/packages/6d/b9/aacedca314f7061f84c021c9eaac9ceac9c57f277e4e9bbb6d998facec8d/pex-1.1.14.tar.gz
https://pypi.python.org/packages/2e/ad/e627446492cc374c284e82381215dcd9a0a87c4f6e90e9789afefe6da0ad/requests-2.11.1.tar.gz
https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz
"
set -euo pipefail

tmp_dir=$(mktemp -d)
data=()

for pex_dep_url in ${pex_deps_urls}; do
    dep_name=`echo ${pex_dep_url} | awk -F "/" '{print $NF}'`
    dep_path="${tmp_dir}/$dep_name"

    wget --quiet --directory-prefix=${tmp_dir} "${pex_dep_url}" || (echo "${pex_dep_url} not found"; exit 1)

    sha_256="$(sha256sum "${dep_path}" | awk '{print $1}')"
    s3_url="s3://zoox-third-party/${sha_256}/${dep_name}"
    if aws s3 ls "${s3_url}" > /dev/null ; then
        echo "WARNING: ${dep_name} is already in S3. Run 'aws s3 rm ${s3_url}' if you'd like to re-upload."
        echo ""
   else
        aws s3 cp --quiet "${dep_path}" "s3://zoox-third-party/${sha_256}/${dep_name}" --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers
    fi

    data+=("url: https://s3-us-west-1.amazonaws.com/zoox-third-party/${sha_256}/${dep_name}, SHA256: ${sha_256}")
done

echo "Uploaded urls and their SHAs are "
printf '%s\n' "${data[@]}"
