source "$EXP_ROOT/experiments/extra.shared.sh"

load_config() {
    source "$EXP_ROOT/configs/nginx.sh"
}

nginx_pre_start() {
    load_config

    if [ "$CALADAN" == "true" ]; then
        echo "No Nginx port for Caladan :/"
        exit 1
    elif [ "$FSTACK" == "true" ]; then
        NGINX="$NGINX_FSTACK"
    fi

    NGINX_TMP_PREFIX="$(mktemp -d -p /tmp)"
    cp "$EXP_ROOT/nginx.conf" "$NGINX_TMP_PREFIX"
    cp "$EXP_ROOT/f-stack.conf" "$NGINX_TMP_PREFIX"

    sed -i "s/{threads}/$THREADS/g" "$NGINX_TMP_PREFIX/nginx.conf"
    sed -i "s/lcore_mask=1/lcore_mask=0x$(printf '%x' $((2 ** THREADS - 1)))/g" "$NGINX_TMP_PREFIX/f-stack.conf"

    if [ "$FSTACK" == "true" ]; then
        sed -i "s/#{fstack_only}#//g" "$NGINX_TMP_PREFIX/nginx.conf"
    fi

    EXPERIMENT_NAME_EXT="t$THREADS"
}

nginx_start() {
    pkill -INT nginx || true
    echo "taskset -c $FIRST_CPU-$((FIRST_CPU + THREADS - 1 - THREAD_TAIL_OFFSET)) $NGINX -c \"$NGINX_TMP_PREFIX/nginx.conf\""
    taskset -c $FIRST_CPU-$((FIRST_CPU + THREADS - 1 - THREAD_TAIL_OFFSET)) $NGINX -c "$NGINX_TMP_PREFIX/nginx.conf" &
    NGINX_PID=$!
    sleep 60
}

nginx_warmup() {
    echo "Warming up Nginx..."
    sudo -u $SSH_USER ssh $NGINX_CLIENT wrk --latency --timeout 1m --duration 1m --threads 8 -c 1000 http://$NGINX_HOST/plaintext
}

nginx_bench() {
    echo "Benchmarking Nginx with $1 connections"
    perf_stat_start "$1"
    sudo -u $SSH_USER ssh $NGINX_CLIENT wrk --latency --timeout 1m --duration 1m --threads 8 -c $1 http://$NGINX_HOST/plaintext | tee "$DATA_OUT/$1.txt"
    perf_stat_stop
}

nginx_stop() {
    pkill -INT "$NGINX_PID" || true
    rm -rf "$NGINX_TMP_PREFIX" || true
}
