#!/bin/bash

if [ -z "$1" ]; then
    echo "2; Usage: $0 <dbs3-path> <warn-limit-hours> <crit-limit-hours> [<s3-monthly-prefix>]"
    exit 1
elif [ -z "$2" ]; then
    echo "2; empty warn limit"
    exit 2
elif [ -z "$3" ]; then
    echo "2; empty crit limit"
    exit 3
fi

DIR="$1"
WARN_LIMIT_HOURS="$2"
CRIT_LIMIT_HOURS="$3"
S3_MONTHLY_PREFIX="$4"

S3_PREFIX_FILE="$DIR/envdir/WALE_S3_PREFIX"
if ! [ -r $S3_PREFIX_FILE ]; then
    echo "0; OK, disabled"
    exit 0
fi

# WALE_S3_PREFIX:
# s3://mapsdb/wal-g/maps_db_main/9.5/

S3_BUCKET=`cut -f3 -d/ $S3_PREFIX_FILE`  # mapsdb
S3_PREFIX=`cut -f4- -d/ $S3_PREFIX_FILE` # wal-g/maps_db_main/9.5/
PGCLUSTER=`cut -f5 -d/ $S3_PREFIX_FILE`  # maps_db_main
PGVERSION=`cut -f6 -d/ $S3_PREFIX_FILE`  # 9.5
PG_DIR="/var/lib/postgresql/$PGVERSION/main"
if [ -r $PG_DIR/recovery.conf ]; then
    echo "0; OK, slave detected"
    exit 0
fi

# check last backup
# 2018-12-07 16:57:57 250562 monthly-wal-g/maps_db_main/9.5/basebackups_005/base_0000000100000C87000000DB_backup_stop_sentinel.json
# or
# 2018-12-12 00:03:24 248503 wal-g/maps_db_main/9.5/basebackups_005/base_0000000100000C8D0000002C_D_0000000100000C8C00000090_backup_stop_sentinel.json

CMD_S3TOOL="/usr/bin/envdir $DIR/envdir /usr/bin/yandex-maps-wiki-s3tool --bucket $S3_BUCKET"
CMD_LIST_BASE="$CMD_S3TOOL --action list --prefix $S3_MONTHLY_PREFIX$S3_PREFIX""base"
TMP_LIST_FILE="/var/tmp/dbs3.$PGCLUSTER.$PGVERSION.${S3_MONTHLY_PREFIX}monitoring.list.tmp"

$CMD_LIST_BASE > $TMP_LIST_FILE
if [ $? -ne 0 ]; then
    echo "1; WARN, error on get listing from S3"
    exit 0
fi

BACKUP_DATE=`grep sentinel $TMP_LIST_FILE | tail --lines 1 | cut -f1,2 -d' '`
if [ -z "$BACKUP_DATE" ]; then
    echo "0; OK, no backups"
    exit 0
fi

NOW_SECONDS=`date +'%s' -d now`
BACKUP_SECONDS=`date +'%s' -d "$BACKUP_DATE"`
AGE_HOURS=$[($NOW_SECONDS - $BACKUP_SECONDS) / 3600]
if [ "$AGE_HOURS" -ge $CRIT_LIMIT_HOURS ]; then
    LEVEL="2;"
elif [ "$AGE_HOURS" -ge $WARN_LIMIT_HOURS ]; then
    LEVEL="1;"
else
    LEVEL="0; OK,"
fi

AGE_DAYS=$[$AGE_HOURS / 24]
echo "$LEVEL age: $AGE_HOURS hours ($AGE_DAYS days), $BACKUP_DATE"
