#!/bin/bash

set -eux

type aws

MAPBOX_ACCESS_TOKEN=$(<~/tokens.json jq -r .mapbox_secret)

curl -X POST "https://api.mapbox.com/uploads/v1/jleedev/credentials?access_token=$MAPBOX_ACCESS_TOKEN" > s3.json

export AWS_ACCESS_KEY_ID=$(<s3.json jq -r .accessKeyId)
export AWS_SECRET_ACCESS_KEY=$(<s3.json jq -r .secretAccessKey)
export AWS_SESSION_TOKEN=$(<s3.json jq -r .sessionToken)
export BUCKET=$(<s3.json jq -r .bucket)
export KEY=$(<s3.json jq -r .key)
export AWS_DEFAULT_REGION=us-east-1

aws s3 cp NationalFile.mbtiles s3://${BUCKET}/${KEY}
jq -s add <(<s3.json jq {url}) <(printf '{"tileset":"jleedev.nationalfile"}') > upload.json

curl -X POST --header "Content-Type:application/json" "https://api.mapbox.com/uploads/v1/jleedev?access_token=$MAPBOX_ACCESS_TOKEN" --data @upload.json > upload-result.json

# nb. contains quotes
UPLOAD_ID=$(<upload-result.json jq .id)

COMPLETE=false
while [[ "$COMPLETE" != true ]]
do
  sleep 15
  curl -s "https://api.mapbox.com/uploads/v1/jleedev?access_token=$MAPBOX_ACCESS_TOKEN" > progress.json
  COMPLETE=$(<progress.json jq "map(select(.id==$UPLOAD_ID))[0].complete")
done
