This script will change network condition randomly over time to simulate a jittering network.

#!/bin/bash

# Network interface (can be changed if needed)
INTERFACE="ens3"

# States
STATE_1="delay 20ms loss 0%"
STATE_2="delay 50ms loss 1%"
STATE_3="delay 100ms loss 5%"
STATE_4="delay 200ms loss 10%"

# State names (for display purposes)
STATE_NAME_1="Good network"
STATE_NAME_2="Moderate network"
STATE_NAME_3="Poor network"
STATE_NAME_4="Very bad network"

# Initial state
current_state=1

# Markov state transition probabilities (you can adjust these values)
declare -A transition_probs=(
    [1]="0.5 0.3 0.15 0.05"
    [2]="0.2 0.5 0.2 0.1"
    [3]="0.1 0.2 0.5 0.2"
    [4]="0.05 0.15 0.3 0.5"
)

# Function to restore normal network conditions
cleanup() {
    echo "Restoring normal network conditions..."
    sudo tc qdisc del dev $INTERFACE root
    exit 0
}

# Set up a trap to call cleanup on script interruption (Ctrl+C)
trap cleanup SIGINT

# Create qdisc on interface if it doesn't exist
if ! tc qdisc show dev $INTERFACE | grep -q "root"; then
    sudo tc qdisc add dev $INTERFACE root netem
else
    sudo tc qdisc replace dev $INTERFACE root netem
fi

# Apply initial state (state 1)
tc qdisc change dev $INTERFACE root netem ${STATE_1}
echo "Initial State: $STATE_NAME_1"

# Simulate 4-state Markov process for network conditions
while true; do
    # Sleep for a random time to simulate different durations in each state
    sleep $((RANDOM % 5 + 1))  # Sleep between 1 and 5 seconds

    # Choose next state based on probabilities
    r=$(awk -v seed=$RANDOM 'BEGIN {srand(seed); print rand()}')
    
    # Transition logic based on probabilities
    if (( $(echo "$r < 0.2" | bc -l) )); then
        next_state=1
    elif (( $(echo "$r < 0.5" | bc -l) )); then
        next_state=2
    elif (( $(echo "$r < 0.75" | bc -l) )); then
        next_state=3
    else
        next_state=4
    fi

    # Apply the new state
    case $next_state in
        1)
            tc qdisc change dev $INTERFACE root netem ${STATE_1}
            echo "State changed to: $STATE_NAME_1"
            ;;
        2)
            tc qdisc change dev $INTERFACE root netem ${STATE_2}
            echo "State changed to: $STATE_NAME_2"
            ;;
        3)
            tc qdisc change dev $INTERFACE root netem ${STATE_3}
            echo "State changed to: $STATE_NAME_3"
            ;;
        4)
            tc qdisc change dev $INTERFACE root netem ${STATE_4}
            echo "State changed to: $STATE_NAME_4"
            ;;
    esac

    current_state=$next_state
done