#!/bin/bash

# Copyright © 2019 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

OUTPUT=""
PERF_DATA=""
RETURN_CODE="0"
for file in `ls /backup/odoo/*.latest`
do
    CONTAINER=$(grep "Container:" $file | cut -d ":" -f 2  | tr -d " ")
    if [[ "$CONTAINER" == 'odoo_oikos' ]] || [[ "$CONTAINER" == 'tuleap_filament_dedicated2' ]] ; then
      continue
    fi
    BYTES=$(grep "Bytes:" $file | cut -d ":" -f 2  | tr -d " ")
    OBJECTS=$(grep "Objects:" $file | cut -d ":" -f 2  | tr -d " ")
    LAST_FULL_BACKUP=$(grep full-signature $file | tail -1)
    LAST_INC_BACKUP=$(grep new-signature $file | tail -1)
    if ([ -n "$LAST_FULL_BACKUP" ] && [ `date -d "${LAST_FULL_BACKUP:5:19}" +%s` -gt `date -d '1 day ago' +%s` ]) || ([ -n "$LAST_INC_BACKUP" ] && [ `date -d "${LAST_INC_BACKUP:5:19}" +%s` -gt `date -d '1 day ago' +%s` ]) 
    then
        OUTPUT+="OK: Container: $CONTAINER, Size: $BYTES, # Files: $OBJECTS, Last-Full-Backup: ${LAST_FULL_BACKUP:5:19}, Last-Incremental-Backup: ${LAST_INC_BACKUP:5:19}\n"
    else 
        OUTPUT+="NOK: Container: $CONTAINER, Size: $BYTES, # Files: $OBJECTS, Last-Full-Backup: ${LAST_FULL_BACKUP:5:19}, Last-Incremental-Backup: ${LAST_INC_BACKUP:5:19}\n"
        RETURN_CODE="2"
    fi
    PERF_DATA+="${CONTAINER}_size=$BYTES ${CONTAINER}_files=$OBJECTS "
done
echo "$OUTPUT | $PERF_DATA"
exit ${RETURN_CODE} 
