#!/usr/bin/env bash

SERIAL_NUM=''
RUN_NUM=''
SHARE_FOLDER='current_training_samples'

help() {
    echo "upload-ai-sample-run - uploads full sample run for ai model retraining to aws share"
    echo
    echo "Syntax: upload-ai-sample-run [-h|s|r|f]"
    echo "h print this help menu"
    echo "s serial number of tower run images are on (number only)"
    echo "r run number (task id) to upload"
    echo "f name of aws share folder to load to (default is current_training_samples)"
    echo
    echo "e.g. upload-ai-sample-run -s 316 -r <run#>"
}

while getopts "hs:r:f:" option; do
    case $option in
        h)
            help
            exit;;
        s)
            SERIAL_NUM="${OPTARG}";;
        r)
            RUN_NUM="${OPTARG}";;
        f)
            SHARE_FOLDER="${OPTARG}";;
        \?)
            echo "Invalid option"
            help
            exit 1;;
    esac
done

if [[ -z ${RUN_NUM} || -z ${SHARE_FOLDER} || -z ${SERIAL_NUM} ]]; then
    echo "Invalid argument: most provide a serial number and run number"
    help
    exit 1
fi

cd /opt/dosis2/replay.run
echo "Creating tar file to upload to aws..."
tar -cvf ${SERIAL_NUM}_run_${RUN_NUM}.tar ./${SERIAL_NUM}_run_${RUN_NUM}
bzip2 ./${SERIAL_NUM}_run_${RUN_NUM}.tar

echo "Uploading tar file to AWS for AI Analysis..."
if aws s3 cp ./${SERIAL_NUM}_run_${RUN_NUM}.tar.bz2 s3://manchac/shares/${SHARE_FOLDER}/${SERIAL_NUM}_run_${RUN_NUM}.tar.bz2; then
    echo "Success!"
    rm -f ./${SERIAL_NUM}_run_${RUN_NUM}.tar.bz2
    exit 0
else
    echo "Failed!"
    echo "Something went wrong with sync from aws"
    exit 1
fi
