#!/bin/bash

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

PGCLUSTERS="$DIR/cfg/pgclusters"
PGVERSIONS="$DIR/cfg/pgversions"
S3_BUCKET_FILE="$DIR/cfg/s3_bucket"

FQDN=`hostname -f`

if [ -f $PGCLUSTERS/$FQDN ]; then
    PGCLUSTER=`cat $PGCLUSTERS/$FQDN`
else
    PGCLUSTER=''
fi
if [ -z "$PGCLUSTER" ] || [ "x_$PGCLUSTER" = "x_<skip>" ]; then
    echo "Skip dbs3 for $FQDN"
    exit 0
fi

if [ -f $PGVERSIONS/$FQDN ]; then
    PGVERSION=`cat $PGVERSIONS/$FQDN`
elif [ -f $PGVERSIONS/$PGCLUSTER ]; then
    PGVERSION=`cat $PGVERSIONS/$PGCLUSTER`
else
    PGVERSION=`cat $PGVERSIONS/default`
fi

echo s3://`cat $S3_BUCKET_FILE`/wal-g/$PGCLUSTER/$PGVERSION/ > $DIR/envdir/WALE_S3_PREFIX

WAL_KEEP_DAYS_DIR="$DIR/cfg/wal_keep_days"
YA_ENV=`cat /etc/yandex/environment.type 2>/dev/null`
if [ -f $WAL_KEEP_DAYS_DIR/$FQDN ]; then
    KEEP_DAYS=`cat $WAL_KEEP_DAYS_DIR/$FQDN`
elif [ -f $WAL_KEEP_DAYS_DIR/$PGCLUSTER ]; then
    KEEP_DAYS=`cat $WAL_KEEP_DAYS_DIR/$PGCLUSTER`
elif [ -f $WAL_KEEP_DAYS_DIR/$YA_ENV ]; then
    KEEP_DAYS=`cat $WAL_KEEP_DAYS_DIR/$YA_ENV`
else
    KEEP_DAYS=`cat $WAL_KEEP_DAYS_DIR/default`
fi
if [ "x_$KEEP_DAYS" = "x_<skip>" ]; then
    echo "Master operations disabled ($PGCLUSTER,$PGVERSION). Skip."
    exit 0
fi


# for potential masters

# enable auto clean wal's
echo $KEEP_DAYS > $DIR/envdir/DBS3_WAL_KEEP_DAYS

CONF_DIR="/etc/postgresql/$PGVERSION/main/conf.d"
PUSH_CMD="/usr/bin/envdir /etc/yandex/maps/wiki/dbs3/envdir /usr/bin/timeout 600 /usr/bin/wal-g wal-push %p"

mkdir -p $CONF_DIR 2>/dev/null \
    && \
echo -e "archive_mode = on\narchive_command = '$PUSH_CMD'" > $CONF_DIR/x_dbs3.conf

if [ -f $DIR/cfg/cron/$PGCLUSTER ]; then
    cp --force $DIR/cfg/cron/$PGCLUSTER /etc/cron.d/yandex-maps-wiki-dbs3-tools-backup
fi
