#!/bin/bash
#
# Take a meta_id and rebuild the run directory when it is fragmented
#   Output will be in ${DATA_CACHE}/REINDEXED_BAG_ORIGINALS
#
# Once a run is rebuilt, move the run directory to ${DATA_CACHE}/INCOMING_LOGS

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

meta_id=$1

DATA_CACHE="/mnt/nautilus_rw/data_cache"
INCOMING="${DATA_CACHE}/INCOMING_LOGS"
REBUILD="${DATA_CACHE}/REINDEXED_BAG_ORIGINALS"
S3_LOGS="s3://zoox-logs"
S3_INCOMING="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}
}

mkdir -p ${REBUILD}/${meta_id}
cd ${REBUILD}/${meta_id}

# Rebuild the ingest directory using:
# 1) Files are already in DATA_CACHE (using a mv)
mv -v ${DATA_CACHE}/$(zoox_inter_path ${meta_id})/${meta_id}* ./
# 2) Files in the S3 final area
aws s3 cp --recursive ${S3_LOGS}/$(zoox_inter_path ${meta_id}) ./ --exclude="*" --include="*${meta_id}*"
# 3) Files still in the S3 Incoming area
aws s3 cp --recursive ${S3_INCOMING}/${meta_id} ./

# Remove the lockfile
rm -f LOCKED

cd -

