#!/usr/bin/env bash

set -e

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

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

dest=$(realpath "${dest}")

mkdir -p "${dest}/"
cd "${dest}/"

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}"