#!/bin/bash

source logging.sh
source config.sh

# Initialize variables for the target pod
target_ip=""
target_if=""

# Find details only for the specific target pod
for pod_name in "${POD_NAMES[@]}"; do
    if [[ "$pod_name" == "$TARGET_POD" ]]; then
        target_ip=$(kubectl get pod "$pod_name" -o jsonpath='{.status.podIP}')
        target_if=$(ip route | grep "$target_ip" | awk '{print $3}')
        log "Target pod found: $pod_name -> $target_ip ($target_if)"
        break
    fi
done

# Safety check: Exit if the pod wasn't found or IP is empty
if [[ -z "$target_ip" ]]; then
    log "Error: Target pod '$TARGET_POD' not found or has no IP."
    exit 1
fi

start_fault_injection() {
    # Using index 0 or specific values since we are targeting one pod
    local pkt_loss=${PKT_LOSS[0]:-"10%"} 
    local pkt_delay=${PKT_DELAY[0]:-"100ms"}

    log "Applying packet loss $pkt_loss and delay $pkt_delay to $target_if ($TARGET_POD: $target_ip)"
    sudo tc qdisc add dev "$target_if" root netem loss "$pkt_loss" delay "$pkt_delay"
}

show_fault_injection() {
    log "$target_if ($TARGET_POD $target_ip): $(sudo tc qdisc show dev $target_if)"
}

stop_fault_injection() {
    log "Deleting traffic control rule on $target_if ($TARGET_POD: $target_ip)"
    sudo tc qdisc del dev "$target_if" root 2>/dev/null || true
}

if [[ $# -eq 0 ]]; then
    echo "Usage: $0 <start|show|stop>"
    exit 1
fi

case $1 in
    start)
        start_fault_injection
        ;;
    show)
        show_fault_injection
        ;;
    stop)
        stop_fault_injection
        ;;
    *)
        echo "Invalid option: $1"
        echo "Usage: $0 <start|show|stop>"
        exit 1
        ;;
esac