#!/bin/bash

restoreDir=/etc/restore
pgsqlDir="$restoreDir/postgresql"

hook_check() {
    if [[ -d "$pgsqlDir" ]]; then
        rm -rf "$pgsqlDir" || exit 1
    fi
}

hook_pre() {
    state=$(nc 127.0.0.1 5400)

    if [[ "$state" != "MASTER" ]]; then
        #backupDate=$(date +"%Y-%m-%d")

        mkdir -p "$pgsqlDir" || exit 2
        /usr/local/sbin/pg_backup -c /etc/postgresql/9.6/main/pg_backup.config
    fi
}

hook_post() {
    rm -rf "$pgsqlDir" || exit 1
}

case "$1" in
    before_check)   hook_check;;
    before_backup)  hook_pre;;
    after_backup)   hook_post;;
esac