#!/usr/bin/env bash

set -euo pipefail

if [[ -z "${1:-}" || "$1" == '--help' || "$1" == '-h' ]]; then
  echo "Usage: $0 META_ID"
  exit 1
fi

meta_id=$1

REBUILD="/tmp/hdd_${meta_id}"
S3_LOGS="s3://zoox-logs"
S3_CHUM="s3://zoox-data-incoming"

# Given a meta-id, parse into the intermediate path
zoox_inter_path() {
    local run=$1; shift
    local year=$(expr ${run} : '\(....\).*')
    local month=$(expr ${run} : '....\(..\).*')
    local day=$(expr ${run} : '......\(..\).*')
    local vehicle=$(expr ${run} : '.*-\(.*\)')
    echo ${year}/${month}/${day}/${vehicle}
}

printf "\nPutting the run files in 'hdd': ${REBUILD}\n\n"
mkdir -p ${REBUILD}/vehicle-chum/

printf "\nDownloading the non chum artifacts\n\n"
aws s3 sync ${S3_LOGS}/$(zoox_inter_path ${meta_id}) ${REBUILD}/. --exclude="*" --include="*${meta_id}*"

printf "\nDownloading chum\n\n"
bazel run //bin:chunk_cp -- --uri=${meta_id} --output=${REBUILD}/vehicle-chum/

printf "\nCompleted\n"