#!/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 "Auto cleaning wal's disabled. SKip."
    exit 0
fi
KEEP_DAYS=`cat $DBS3_WAL_KEEP_DAYS_FILE`

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`
if [ -r /var/lib/postgresql/$PGVERSION/main/recovery.conf ]; then
    echo "PosgreSQL ($PGCLUSTER,$PGVERSION) is in recovery mode. Skip."
    exit 0
fi

S3_BUCKET=`cut -f3 -d/ $S3_PREFIX_FILE`
S3_PREFIX=`cut -f4-6 -d/ $S3_PREFIX_FILE`
if [ -z "$S3_BUCKET" ] || [ -z "$S3_PREFIX" ]; then
    echo "Invalid S3 params: $S3_BUCKET, $S3_PREFIX"
    exit 1
fi
S3_PREFIX_WAL="$S3_PREFIX/wal"


S3_TOOL="/usr/bin/yandex-maps-wiki-s3tool"
if ! [ -x $S3_TOOL ]; then
    echo "Can not execute $S3_TOOL with params: $S3_BUCKET, $S3_PREFIX_WAL, $KEEP_DAYS"
    exit 2
fi

sleep $[$RANDOM/(32767/30)] # sleep random 0..30 seconds

envdir $DIR/envdir $S3_TOOL \
    --action clean \
    --incremental-clean \
    --limit 100 \
    --bucket $S3_BUCKET \
    --prefix $S3_PREFIX_WAL \
    --keep $KEEP_DAYS
