folder_name="exp1_results"

echo "Output folder: $folder_name"

if [ -d "$folder_name" ]; then
    echo "Output folder '$folder_name' already exists."
    echo "Removing all files in '$folder_name'..."
    rm -r "$folder_name"/*
else
    echo "Creating output folder '$folder_name'..."
    mkdir "$folder_name"
fi

# Write column names to csv file
echo "number_active_pods,cpu_usage" > $folder_name/pod_info.csv

echo "Starting collection of CAD metrics..."
while true; do
    list=($(kubectl get pods --namespace tfs | grep l3-centralized | awk '{print $1}'))
    #kubectl -n "tfs" cp $pod_name:exp_1.csv $folder_name/$pod_name.csv -c server
    echo "Currently running pods:"

    for item in "${list[@]}"; do
        echo "Pod: $item"
        echo "Copying CAD metrics csv file to $folder_name/response_times_$item.csv"
        kubectl -n "tfs" cp $item:response_times.csv $folder_name/response_times_$item.csv -c server
    done
    
    echo "Getting number of currently active pods and CPU usage..."
    number_pods=$(kubectl get pods --namespace tfs | grep l3-centralized | wc -l)
    cpu_usage=$(kubectl --namespace tfs get all | grep autoscaling/l3-centralizedattackdetectorservice-hpa  | awk '{print $3}')

    # check that cpu_usage does not contain "unknown"
    if [[ $cpu_usage == *"unknown"* ]]; then
        cpu_usage=0
    fi

    echo
    echo "Number of currently active pods: $number_pods"
    echo "CPU usage: $cpu_usage"
    echo
    
    echo "Writing number of currently active pods and CPU usage to $folder_name/pod_info.csv"
    echo "$number_pods,$cpu_usage" >> $folder_name/pod_info.csv
    sleep 1

    # check if file "stop_exp1" exists
    if [ -f "stop_exp1" ]; then
        echo "File 'stop_exp1' found. Stopping experiment."
        break
    fi
done

echo "Collection of CAD metrics stopped."
rm stop_exp1
