#!/bin/bash
# Criado por Guilherme Festozo, inspirado no Marcelo Gondim do BrasilPeeringForum, mas editado por Junior Corazza para suportar EXABGP
# Lista de domínios para testar:
dominios_testar=(
www.google.com
www.terra.com.br
www.uol.com.br
www.globo.com
www.facebook.com
www.youtube.com
www.twitch.com
www.discord.com
www.debian.org
www.redhat.com
)
corte_taxa_falha=30  # Percentual de falhas para remover BGP
resolver="127.0.0.1"

#Verifica se o ExaBGP ja esta rodando
if systemctl status exabgp | grep "running" &> /dev/null; then
    bgp_removido=false  #BGP ja esta removido
else
    bgp_removido=true  #BGP esta ativo
fi

echo $bgp_removido

remove_bgp() {
    echo "Removendo BGP"
    if ! $bgp_removido; then  # Só remove se ainda não estiver removido
        systemctl stop exabgp
        /etc/unbound/telegram.sh "O DNS falhou e o ExaBGP foi desativado. Verificar manualmente!"
        bgp_removido=true
    fi
}

adiciona_bgp() {
    echo "Adicionando BGP"
    if $bgp_removido; then
        systemctl start exabgp
	/etc/exabgp/announce.sh
        /etc/unbound/telegram.sh "O DNS voltou e o ExaBGP foi restaurado!"
    fi
}

testa_dns() {
    local falhas=0
    local total=${#dominios_testar[@]}

    echo "Total de domínios testados: $total" >&2
    for site in "${dominios_testar[@]}"; do
        echo -n " - Testando $site... " >&2
        if ! timeout 3 host "$site" "$resolver" &> /dev/null; then
            ((falhas++))
            echo "[Falhou]" >&2
        else
            echo "[OK]" >&2
        fi
    done

    local taxa_falha=$((falhas * 100 / total))
    echo "Falhas: $falhas/$total ($taxa_falha%)" >&2
    echo "$taxa_falha"  # Só isso será capturado em taxa_falha
}

# Primeira validação
taxa_falha=$(testa_dns)
# Se falhou acima do limite, tenta reiniciar Unbound
if [ "$taxa_falha" -ge "$corte_taxa_falha" ]; then
    #/etc/unbound/telegram.sh "O DNS apresentou uma alta taxa de falha. Tentando reiniciar Unbound..."
    systemctl restart unbound
    sleep 5  # Da tempo para o servico iniciar antes de testar de novo

    # Segunda validacao�apos�restart
    taxa_falha=$(testa_dns)
    if [ "$taxa_falha" -ge "$corte_taxa_falha" ]; then
        remove_bgp
        exit 1
    fi
fi

# Se o BGP foi removido, adiciona de volta
if $bgp_removido; then
    adiciona_bgp
fi

exit 0
