#!/bin/bash
#
# recordum_export_sensor_quick
#
# v0.1 2019-11-21 RE
# v0.2 2020-01-16 RE
#
# script to export sensor data

MYSELF=$(basename "$0")
# stop script if $ALERT Percent are in use
ALERT=80

# helper
script_help() {
    cat <<EOF
${MYSELF} help:

This script creates an export for sensor data. It needs root privileges!

Usage: ${MYSELF} -h <HOST> \\
                 -u <URL> \\
                 -m <MAX_STEPS> \\
                 -s <STEP_TIME>

where:
    <HOST>      ... ip4 address of target system
    <URL>       ... URL build according document recordum_HTTP_Download_Interface_V2.04
    <MAX_STEPS> ... max allowed steps for a CGI request
                    param: Download_MaxTime (seconds) / step time (seconds) = max steps
    <STEP_TIME> ... number of seconds for each step

EOF
}

if [[ $# -lt 1 ]]; then
    script_help
    exit 1
fi

while getopts "h:u:m:s:" option; do
    case ${option} in
    h)
        TARGET_HOST=$OPTARG
        ;;
    u)
        TARGET_URL=$OPTARG
        ;;
    m)
        TIMEOUT_MAX_STEPS=$OPTARG
        ;;
    s)
        TIMEOUT_STEP_TIME=$OPTARG
        ;;
    *)
        script_help
        exit 2
        ;;
    esac
done

if [ "$( id -un )" != recordum ]; then
    echo "$MYSELF needs to be run as recordum. You are $USER."
    exit 3
fi

# test for space
USAGE=$(df -h /backup | grep '/backup' | awk '{ print $5 }' | cut -d '%' -f1)
if [[ ${USAGE} -ge ${ALERT} ]]; then
    echo "Running out of space for exports. /backup (${USAGE}%)"
    exit 4
fi

EXPORTER=export_sensor_quick
COUNT=0
SEARCH="<STATUS>OK"
while :
do
    # the -- indicates that all subsequent arguments should go to the script and not to the PHP interpreter binary
    XML_RESPONSE=$( /usr/local/recordum/dataproc/${EXPORTER} -- "${TARGET_URL}" )
    # file may be fetched
    if [[ ${XML_RESPONSE} =~ ${SEARCH} ]]; then
        break;
    fi
    #echo "###count###${COUNT}###response###${XML_RESPONSE}###/response###"
    # timeout handling
    let COUNT++
    if (( COUNT == TIMEOUT_MAX_STEPS )); then
        break
    fi
    sleep ${TIMEOUT_STEP_TIME}
done

# if we reached the end of the loop exit with a failure
if [[ ${COUNT} == ${TIMEOUT_MAX_STEPS} ]]; then
    echo "${EXPORTER}: failed to create a valid export file. TIMEOUT reached!"
    exit 5
fi

echo "###host###http://${TARGET_HOST}###/host###
      ###response###${XML_RESPONSE}###/response###"
# full success
exit 0
