#!/usr/bin/env bash

if [[ -z "$1" || "$1" == "-h" ]]; then
    echo "Usage: $0 <version_num>"
    echo "Example: $0 3.0.7-1"
    echo "See README.md for more info"
    exit 1
fi

set -euo pipefail

version="${1}_amd64"

deb_names="iperf3_${version}.deb libiperf0_${version}.deb"
tmp_dir=$(mktemp -d)
urls=()

for deb_name in ${deb_names}; do
    deb_url="http://us.archive.ubuntu.com/ubuntu/pool/universe/i/iperf3/${deb_name}"
    deb_path="${tmp_dir}/$deb_name"

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

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

    urls+=("https://s3-us-west-1.amazonaws.com/zoox-third-party/${sha_256}/${deb_name}")
done

echo "S3 urls to update in vars/main.yml"
printf '%s\n' "${urls[@]}"
