#!/usr/bin/env bash


#
# Copyright 2016-2022 Hedera Hashgraph, LLC
#
# This software is the confidential and proprietary information of
# Hedera Hashgraph, LLC. ("Confidential Information"). You shall not
# disclose such Confidential Information and shall use it only in
# accordance with the terms of the license agreement you entered into
# with Hedera Hashgraph.
#
# HEDERA HASHGRAPH MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
# THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
# TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE, OR NON-INFRINGEMENT. HEDERA HASHGRAPH SHALL NOT BE LIABLE FOR
# ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
# DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
#

# repeatedly block and unblock TCP ports used by gossip

set -eE

# wait a while for swirlds jar to start
sleep 20

trap ctrl_c INT

#
# Cleanup all firewall rules if this script is terminated unexpecctedly
#
function ctrl_c() {
    echo "recover default firewall rules"
    sudo iptables --flush
    exit
}


while true; do
    echo "Block input and output gossip port"
    sudo -n iptables -A INPUT -p tcp --dport 30124:30224 -j DROP
    sudo -n iptables -A OUTPUT -p tcp --sport 30124:30224 -j DROP

    # sleep long enough to cause the time out of sync listner
    sleep $(( ( RANDOM % 5 )  + 8 ))

    echo "Enable input and output gossip port"
    sudo -n iptables -D INPUT -p tcp --dport 30124:30224 -j DROP
    sudo -n iptables -D OUTPUT -p tcp --sport 30124:30224 -j DROP

    # sleep long enough to sync with others to catch up some events
    sleep $(( ( RANDOM % 5 )  + 8 ))
done

