#!/bin/bash

# CVE_ID="CVE-2019-5736"
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 main
tmux new-session -d -s trigger
tmux new-session -d -s record

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'

    attack_cmd="kubectl cp main $POD_ID:/ -c wordpress && kubectl exec -it $POD_ID -c wordpress -- /main"
    trigger_cmd="kubectl exec -it $POD_ID -c wordpress -- /bin/bash"

    # echo $attack_cmd
    tmux send -t "main" "$attack_cmd" ENTER
    tmux send -t "trigger" "$trigger_cmd" ENTER
    # tmux send -t "trigger" "echo 'cat /etc/shadow > /tmp/shadow && chmod 777 /tmp/shadow && cat /tmp/shadow' > /etc/runc-tmp && chmod 777 /etc/runc-tmp && bash /etc/runc-tmp" ENTER
    tmux send -t "trigger" "sleep 0.2 && exit" ENTER

    # stop record
    kubectl exec -it $POD_ID -c wordpress -- logger 'Attack Stop'
    sleep 1
    tmux send -t "record" "C-c" ENTER
    
    FILE_NUMBER=$((FILE_NUMBER + 1))
    sleep 10 && echo "Finish $FILE_NUMBER"
done

# clean up
tmux kill-session -t main
tmux kill-session -t trigger
minikube delete


