#!/bin/bash

if [ -z "$1" ]; then DIR=$PWD; else DIR=$1; fi # pwd - for development

DBS3_WAL_KEEP_DAYS_FILE="$DIR/envdir/DBS3_WAL_KEEP_DAYS"
if ! [ -r $DBS3_WAL_KEEP_DAYS_FILE ]; then
    echo "BACKUP disabled. SKip."
    exit 0
fi

S3_PREFIX_FILE="$DIR/envdir/WALE_S3_PREFIX"
if ! [ -r $S3_PREFIX_FILE ]; then
    echo "Can not find $S3_PREFIX_FILE. Skip."
    exit 0
fi

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

PGCLUSTER=`cut -f5 -d/ $S3_PREFIX_FILE`
PGVERSION=`cut -f6 -d/ $S3_PREFIX_FILE`
PG_DIR="/var/lib/postgresql/$PGVERSION/main"
if [ -r $PG_DIR/recovery.conf ]; then
    echo "PosgreSQL ($PGCLUSTER,$PGVERSION) is in recovery mode. Skip."
    exit 0
fi

if ! [ -w $PG_DIR/PG_VERSION ]; then
    echo "Can not access to PosgreSQL ($PGCLUSTER,$PGVERSION) directory. Skip."
    exit 0
fi

IS_SLAVE=`psql --tuples-only --no-align --command 'SELECT pg_is_in_recovery()' 2>/dev/null`
if [ "x_$IS_SLAVE" != "x_f" ]; then
    echo "Master not detected. SKip."
    exit 0
fi


# delete old backups
WAIT_LIMIT=$[3*60*60] # timeout 3h
KEEP_DAYS=`cat $DBS3_WAL_KEEP_DAYS_FILE`
/usr/bin/envdir $DIR/envdir \
    /usr/bin/timeout $WAIT_LIMIT \
    /usr/bin/wal-g delete retain FIND_FULL $KEEP_DAYS --confirm

# create new backup
WAIT_LIMIT=$[20*60*60] # timeout 20h
/usr/bin/envdir $DIR/envdir \
    /usr/bin/timeout $WAIT_LIMIT \
    /usr/bin/yandex-maps-wiki-dbs3-wal-g-smart-backup.sh backup-push $PG_DIR
