#!/bin/bash
#
# recordum_export_sensor
#
# v0.1 2014-06-20 RE
#
# script to export sensor data

MYSELF=$( basename $0 )
TIMESTAMP=$( date +%Y%m%d-%H%M%S )
PSQLBIN=/usr/bin/psql

# stop script if $ALERT Percent are in use
ALERT=80

# get our ID
# serial remove any dots
SERIAL=$( /usr/local/recordum/dataproc/getserial 2>/dev/null |tr . _ )
PRODUCT=$( cat /usr/local/recordum/PRODUCT_CODE )
if [[ -z "$PRODUCT" || ${SERIAL} == "UNKNOWN" ]]
then
    echo "Unable to identify product or serial"
    exit 2
fi

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

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

Usage: ${MYSELF} -i <ID> \\
             [ -S <start time> ] \\
             [ -T <stop time> ]

where:
    <ID>         ... ID of the export defition
    <start time> ... start time: 2014.06.12 12:20:00
    <stop time>  ... stop time : 2014.06.12 18:40:00

EOF
}

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

while getopts "i:S:T:" option
do
    case ${option} in
        i) EXPID=$OPTARG
            ;;
        S) STARTDT=$OPTARG
            ;;
        T) STOPDT=$OPTARG
            ;;
        *) script_help
            exit 3
            ;;
    esac
done

# backup directory
BAKDIR=/backup/exports/sensors
# db export file name without an ending!
DBFILE=exp.sensors.man.${PRODUCT}.${SERIAL}.${TIMESTAMP}

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 21
fi

# create the db export
DATAPROC=/usr/local/recordum/dataproc
EXPORTER=exporttofile
if [[ -n "$STARTDT" ]] && [[ -n "$STOPDT" ]]
then
    NEWFILEID=$( ${DATAPROC}/${EXPORTER} -id ${EXPID} -f ${BAKDIR}/${DBFILE} -s \'${STARTDT}\' -t \'${STOPDT}\' )
elif [[ -n "$STARTDT" ]]
then
    NEWFILEID=$( ${DATAPROC}/${EXPORTER} -id ${EXPID} -f ${BAKDIR}/${DBFILE} -s \'${STARTDT}\' )
elif [[ -n "$STOPDT" ]]
then
    NEWFILEID=$( ${DATAPROC}/${EXPORTER} -id ${EXPID} -f ${BAKDIR}/${DBFILE} -t \'${STOPDT}\' )
else
    NEWFILEID=$( ${DATAPROC}/${EXPORTER} -id ${EXPID} -f ${BAKDIR}/${DBFILE} )
fi

# return code of zero means we have a valid ID
ERRCODE=$?
if [[ ! ${ERRCODE} -eq 0 ]]
then
    echo "${EXPORTER}: failed to create a valid export file. <${ERRCODE}>"
    exit 5
fi
# test if NEWFILEID is a number using regular expression
re='^[0-9]+$'
if ! [[ $NEWFILEID =~ $re ]]; then
    echo "${EXPORTER}: not a number. ID: <${NEWFILEID}>"
    exit 51
fi
NEWFILE=$( ${PSQLBIN} -Upostgres --set ON_ERROR_STOP=on -c"SELECT filename_path FROM exp_waytofile WHERE id = ${NEWFILEID}" -A -t recordum )
if [[ "$NEWFILE" == "" ]]
then
    echo "${EXPORTER}: unable to read new file name. ID: <${NEWFILEID}>"
    exit 52
fi
if [[ ! -f ${NEWFILE} ]]
then
    echo "${EXPORTER}: no valid file was written to disk."
    exit 53
fi
# cleanup - search for compression file endings
if [[ ${NEWFILE} =~ .*zip ]] || [[ ${NEWFILE} =~ .*tgz ]]
then
    # remove the file ending with the point
    FILE2CLEAN=$( echo "$NEWFILE" | sed -r 's/\.zip|\.tgz+$//' )
    if [[ -f ${FILE2CLEAN} ]]
    then
        rm -f ${FILE2CLEAN}
    fi
fi

# set default owner
/bin/chown recordum:adm ${NEWFILE}

echo "Export of $NEWFILE is DONE"
# full success
exit 0
