#!/bin/bash

{% set dnsmaster_dns_host = prop('dnsmaster.dns.host') %}

ABYSSYNC_DISABLE_FLAG=/etc/yandex/abyssync.disabled
APP_CLOSE_FILE=/var/run/maintenance.file

fail() {
    echo "$1 Fail"
    exit 1
}

success() {
    echo "$1 Success"
    exit 0
}

auto_open () {
    ip6tables -F
    rm -f $APP_CLOSE_FILE
}

auto_close () {
    ip6tables -A INPUT -i ip6tnl0 --proto tcp -d {{ dnsmaster_dns_host }} --dport 53 -j REJECT
    ip6tables -A INPUT -i ip6tnl0 --proto tcp -d {{ dnsmaster_dns_host }} --dport 80 -j REJECT

    touch $APP_CLOSE_FILE
}

balancer_close() {
    touch $ABYSSYNC_DISABLE_FLAG
    auto_close
}

balancer_open() {
    rm -f $ABYSSYNC_DISABLE_FLAG
    auto_open
}

execute() {
    $1 || fail "$1"
    success "$1"
}

if [[ "$1" == "open" ]]; then
    execute balancer_open
elif [[ "$1" == "close" ]]; then
    execute balancer_close
elif [ -n "$1" ]; then
    execute $1
else
    echo "Usage: $0 <open|close|auto_open|auto_close>"
    exit 1
fi
