#! /bin/sh

# Pull recent data from RBR data hosting.
#
# Copyright (c) 2019, 2020 RBR Ltd. Distributed under the terms of the Apache
# License v2.0.
#
# History:
#
# 2019-12-13 1.0.0: Initial release.
# 2020-02-06 1.1.0: More help. macOS compatibility. Output file option.

SCRIPT_VERSION="1.1.0"

echo "getcsvdata.sh v$SCRIPT_VERSION"

if [ $# -lt 4 ] || [ $1 == "-h" ] || [ $1 == "--help" ]
then
    cat <<USAGE 1>&2
Usage: $0 <customer> <serial> <start> <end> [output]
Pull a CSV export of instrument data from an RBR data hosting instance.

customer:   the customer URL slug
instrument: the instrument serial number
start, end: export date range as ISO-8601 dates (YYYY-MM-DD)
output:     optional output filename

If the output filename is not provided, output will be written to
RBR-<instrument>.csv.

Example: $0 rbr 110099 2017-09-05 2020-12-31
USAGE
    exit 1
fi

# Which data hosting instance are we retrieving data from?
if [ -z "$DH_INSTANCE" ]
then
    DH_INSTANCE="https://data.rbr-global.com"
fi

# How frequently we expect new instrument data to arrive; how frequently we'll
# repoll/replace the output file.
if [ -z "$UPDATE_PERIOD" ]
then
    UPDATE_PERIOD=600 # seconds
fi

CUSTOMER="$1" # customer URL slug
INSTRUMENT="$2" # serial number
DEPLOYMENT_START="$3" # ISO-8601 date
DEPLOYMENT_FINISH="$4" # ISO-8601 date
OUTPUT="$5" # filename

if [ -z "$OUTPUT" ]
then
    OUTPUT="RBR-$INSTRUMENT.csv"
fi

log ()
{
    echo "$(date -u +%FT%T%z)" "$@"
}

while true
do
    log "Fetching new data..."
    # The download endpoint will automatically suggest a filename via the
    # Content-Disposition HTTP header, which we could use via the cURL options
    # `--remote-name --remote-header-name`. However, we want to ensure the
    # output file is always intact, even if out-of-date, so we'll download to a
    # temporary file and replace the output file after the download completes.
    new_output="$(mktemp "$OUTPUT".XXXXXX)"
    curl --location \
         --output "$new_output" \
         --compressed \
         "$DH_INSTANCE/$CUSTOMER/download/$INSTRUMENT?from=$DEPLOYMENT_START&to=$DEPLOYMENT_FINISH"
    success=$?

    if [ "$success" = 0 ]
    then
        chmod 0644 "$new_output"
        mv "$new_output" "$OUTPUT"
    else
        log "cURL failed with exit code $success! Will try again in" \
            "$UPDATE_PERIOD seconds."
        rm "$new_output"
    fi

    log "Sleeping for $UPDATE_PERIOD seconds..."
    sleep $UPDATE_PERIOD
done
