#!/usr/bin/env bash

set -u -e -o pipefail


function usage() {
cat << EOF
Usage:
  download_logs.sh [OPTIONS] <date> <name>

  <date> the date the log was recorded
  <name> the name of the log (at least the prefix)

  OPTIONS:
    --local, -l path: the local path where to get the logs (i.e. /mnt/nautilus/data_cache)
      If this option is not given it will get the logs from AWS
    --dry-run, -n: only show the logs found, do not download anything
    --output-dir, -o: where to download the logs (default: current directory)
    --no-vel, -v: do not download the velodyne bag
EOF
}

OUTPUT_DIR='.'

while [[ $# > 0 ]]
do
  case "$1" in
    -h|--help)
    usage
    exit 0
    ;;
    --local|-l)
    LOCAL_PATH="$2"
    shift # past argument
    ;;
    --dry-run|-n)
    DRY_RUN=1
    ;;
    --output-dir|-o)
    OUTPUT_DIR="$2"
    shift # past argument
    ;;
    --no-vel|-v)
    NO_VEL=1
    ;;
    *)
    if [ ! -v DATE ]
    then
      DATE="$1"
    elif [ ! -v NAME ]
    then
      NAME="$1"
    fi
  esac
  shift # past argument or value
done

if [ -v LOCAL_PATH ]
then
  ROOT_PATH=$LOCAL_PATH
else
  ROOT_PATH="s3://zoox-logs-pdx"
fi

# convert input date into YYYY/MM/DD/ path
DATE_PATH=`date --date=${DATE} "+${ROOT_PATH}/%Y/%m/%d/"`

echo "Searching for '$NAME'  in '$DATE_PATH' ..."

if [ -v LOCAL_PATH ]
then
  FILES=$(find "$DATE_PATH" -name "${NAME}*")
else
  # get a list of files, use s3 to list them recursively, tr -s removes repeated spaces, so that cut can use the space as a delimiter
  # at that point -f4 extracts the 4th field which is the path relative to DATE_PATH
  # grep is used to filter on the log names we actually care about
  FILES=`aws s3 ls --recursive $DATE_PATH | tr -s " " | cut --delimiter=" " -f4 | grep "$NAME"`
fi

echo "===================== FOUND ========================"
echo "$FILES"
echo "===================================================="

[ -v DRY_RUN ] && exit 0

echo "Syncing to '$OUTPUT_DIR'"
echo "===================================================="

for F in $FILES; do
    DIR=`dirname $F`
    FN=`basename $F`

    [[ -v NO_VEL ]] && [[ $FN == *.velodyne.bag ]] && continue

    if [ -v LOCAL_PATH ]
    then
      rsync -tP "$F" "$OUTPUT_DIR"
    else
      echo "aws s3 sync --exclude=\"*\" --include=\"${FN}\" $ROOT_PATH/$DIR $OUTPUT_DIR"
      aws s3 sync --exclude="*" --include="$FN" $ROOT_PATH/$DIR $OUTPUT_DIR
      [ $? ] || (echo "error downloading $ROOT_PATH/$DIR/$F" >&2; exit 1)
    fi
done

echo "====================================================="
echo "Done."
