#!/usr/bin/env bash

set -e

pref="${1}"
s3_key="${2}"
s3_secret="${3}"
s3_host="${4}"
s3_bucket="${5}"

if test -z "$pref" || test -z "$s3_key" || test -z "$s3_secret" || test -z "$s3_host" || test -z "$s3_bucket"; then
	echo "Usage: ${0} <pref> <s3_key> <s3_secret> <s3_host> <s3_bucket>"
	exit 1
fi

mkdir -p "$(dirname $(realpath "${BASH_SOURCE[0]}"))/../data/"
cd "$(dirname $(realpath "${BASH_SOURCE[0]}"))/../data/"

file="${pref}.zip"

echo "Downloading ${pref}..."

ressource="/${s3_bucket}/${file}"
content_type="application/octet-stream"
date=$(date --utc -R)

signature=$(echo -en "GET\n\n${content_type}\n${date}\n${ressource}" | openssl sha1 -hmac "${s3_secret}" -binary | base64)

curl -X GET \
	 --silent \
	 -H "Date: ${date}" \
	 -H "Content-Type: ${content_type}" \
	 -H "Authorization: AWS ${s3_key}:${signature}" \
	 "${s3_host}${ressource}" \
	 -o "${file}"

unzip -o "${file}" > /dev/null
rm "${file}"
