#!/usr/bin/env bash

set -euo pipefail

if [[ -z "$1" || -z "$2" || "$1" == "-h" ]]; then
    echo "Usage: $0 <libcuda_deb_url> <nvidia_deb_url>"
    echo "Example: $0 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu/pool/main/n/nvidia-graphics-drivers-390/libcuda1-390_390.25-0ubuntu0~gpu14.04.1_amd64.deb http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu/pool/main/n/nvidia-graphics-drivers-390/nvidia-390_390.25-0ubuntu0~gpu14.04.1_amd64.deb"
    echo "See README.md for more info"
    exit 1
fi

set -euo pipefail

apt_deb_urls="$1 $2"
tmp_dir=$(mktemp -d)
urls=()

for deb_url in ${apt_deb_urls}; do
    deb_name=`echo ${deb_url} | awk -F "/" '{print $NF}'`
    deb_path="${tmp_dir}/$deb_name"

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

    sha_256="$(sha256sum "${deb_path}" | awk '{print $1}')"
    package_version=$(dpkg-deb --info ${deb_path} | grep 'Version' | awk '{print $NF}')

    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+=("package_version: ${package_version}, SHA256: ${sha_256}, URL: https://s3-us-west-1.amazonaws.com/zoox-third-party/${sha_256}/${deb_name}")
done

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