#tc qdisc add dev eth0 root netem delay 100ms rate 8192kbit

build()
{
    docker build -t hare1039/mpeg-dash-ipfs:$1 ${IPFS_ABR_BASE}/docker;
}

build-raw()
{
    docker build -t hare1039/mpeg-dash-ipfs:$1 ${IPFS_ABR_BASE}/rawdocker/;
}

wait_port()
{
    while ! nc -q0 "$1" "$2" < /dev/null > /dev/null 2>&1; do
        sleep 1;
    done
}

local-random()
{
    shuf -i 1-99999 -n 1;
}

testpf()
{
    local page="$1";
    local outputname=$(ipfs_test "http://123.123.123.123" "$page" --print_name_only True);
    if [[ -f $outputname ]]; then
        echo "$outputname exist. skip"
        return
    fi
    touch $outputname;

    build cap-${BACKDELAY}-${BACKRATE};
    build-raw cap-raw-${FRONTDELAY}-${FRONTRATE};

    #local container_name="bed_${BACKDELAY}_${BACKRATE}_$(local-random)";

#    DELAY=${BACKDELAY} RATE=${BACKRATE} SECOND_DOCKER_NETWORK="" ETH1DELAY="0ms" ETH1RATE="666872mbit" ./launch.sh $container_name cap-${BACKDELAY}-${BACKRATE};

    ssh -p 9995 zhenwu@130.245.145.107 'docker rm -f gateway'
    ssh -p 9995 zhenwu@130.245.145.107 'docker run -d --name gateway -p 28080:28080 -p 28081:28081 -p 24001:24001 hare1039/telescope:0.3.0'

    until ssh -p 9995 zhenwu@130.245.145.107 "docker exec  gateway ipfs --config /ipfs swarm connect '${STORAGE_HOST}'" | grep -q "success"; do
        sleep 1;
        echo "waiting connecting to ${STORAGE_HOST}"
    done

    STORAGE_HOST_2=/ip4/34.142.95.76/tcp/4001/p2p/12D3KooWMCuWaCmkJ5GjxiptDZg2wJECMe6toCWbTRaTMSAC7iX9
    until ssh -p 9995 zhenwu@130.245.145.107 "docker exec  gateway ipfs --config /ipfs swarm connect '${STORAGE_HOST_2}'" | grep -q "success"; do
        sleep 1;
        echo "waiting connecting to ${STORAGE_HOST_2}"
    done



    local container_name_raw="bedraw_${FRONTDELAY}_${FRONTRATE}";
    echo "name: $container_name_raw";
#
#    local IPX=$(docker exec $container_name bash -c "ip addr show eth0 | grep --color=never -Po 'inet \K[\d.]+'");
#    IPX=${IPX%$'\r'}
#    export PROXY_SOURCE=$IPX;
#
    DELAY="0ms" RATE="666872mbit" REPO="${IPFS_ABR_BASE}/ipfs-mount-dummy" ETH1DELAY="$FRONTDELAY" ETH1RATE="$FRONTRATE" ./launch.sh $container_name_raw cap-raw-${FRONTDELAY}-${FRONTRATE};

    local IP=$(docker exec $container_name_raw bash -c "ip addr show eth1 | grep --color=never -Po 'inet \K[\d.]+'");
    IP=${IP%$'\r'}
#
#
    echo "START TEST" "$IP" "$IPX" "$page" "$container_name_raw" "$REPO" "$PROXY_SOURCE";
    wait_port "$IP" "8080";
    sleep 5;

    ssh -p 9995 zhenwu@130.245.145.107 'docker exec gateway ipfs --config /ipfs log level dht debug'
    ssh -p 9995 zhenwu@130.245.145.107 'docker exec gateway ipfs --config /ipfs log level bitswap debug';

    ipfs_setcache "$container_name" "$container_name_raw" "$EXIST_BUF_SIZE";
    ipfs_test "$IP" "$page";
#    ipfs_test "127.0.0.1" "$page";

#    docker rm -f $container_name;
    docker rm -f $container_name_raw;
    ssh -p 9995 zhenwu@130.245.145.107 'docker exec gateway cat /ipfs/fulllog.txt' > fulllog.buf-${EXIST_BUF_SIZE}.${RANDOM}.txt
    ssh -p 9995 zhenwu@130.245.145.107 'docker rm -f gateway'

}

curl-retry()
{
    local counter=0;
    while ! curl -H "clientID: $1" --silent -o /dev/null "$2" ;do
        echo "retrying $2";
        counter=$((counter + 1));
        if [[ $counter -gt "$3" ]]; then
            echo "cancel retry $2";
            break;
        fi
    done
}


ipfs_setcache()
{
    #    local storage_container=$1;
#    docker run -d --name bedrowlocaldocker -v /mnt/d_drive/ipfs-abr-test:/v -p 6000:4001 ubuntu:20.04 ./v/ipfs --config /v/ipfs-mount1 daemon
    local proxy_container=$2;
    local times=$3;
    echo "Start as";
#    docker exec -it $storage_container sh -c "tc qdisc";
    docker exec -it $proxy_container sh -c "tc qdisc";

#    docker exec -it $storage_container sh -c "tc qdisc del dev eth0 root";
    docker exec -it $proxy_container sh -c "tc qdisc del dev eth0 root";
    docker exec -it $proxy_container sh -c "tc qdisc del dev eth1 root";
    local IPs=$(docker exec $proxy_container bash -c "ip addr show eth1 | grep --color=never -Po 'inet \K[\d.]+'");
    IPs=${IPs%$'\r'}

    local url="http://$IPs:${PORT}/${PATHADDR}";
    local clientID="$(local-random)-debug";
    local fulllist=($(cat qualist.txt));
    local step=1;

    curl -F "setup=1" -F "prefetch=0" "http://$IPs:${PORT}/settings" --silent -o /dev/null;
    curl-retry "$clientID" "$url/${fulllist[0]}" 1000;
    while (( $step < ${#fulllist[@]} )); do
#        local randlist=($(shuf -i 0-10 -n $times --random-source=<(get-seeded-random $RANDOM)));
        for i in ${PRESET_BUFLEVEL[@]}; do
            local ID=$(bc <<< "$step + $i");
            waiter 10;
            #            echo "${fulllist[${ID}]}";
            if [[ "${fulllist[${ID}]}" != "" ]]; then
                curl-retry "$clientID" "$url/${fulllist[${ID}]}" 15 &
            fi
            sleep 0.2;
        done
        step=$(bc <<< "$step + 11");
    done

    wait < <(jobs -p);
    curl -F "setup=1" -F "prefetch=0" -F "policy=${MPDPOLICY}" "http://$IPs:${PORT}/settings" --silent -o /dev/null;

#    docker exec -it $storage_container sh -c "tc qdisc add dev eth0 root netem delay $BACKDELAY rate $BACKRATE";
    docker exec -it $proxy_container sh -c "tc qdisc add dev eth1 root netem delay $FRONTDELAY rate $FRONTRATE";
    echo "Restored as"
    #    docker exec -it $storage_container sh -c "tc qdisc";
#    docker rm -f bedrowlocaldocker;
    docker exec -it $proxy_container sh -c "tc qdisc";
}

waiter()
{
    while [[ $(jobs | wc -l) -ge $1 ]]; do sleep 1; done
}

get-seeded-random()
{
    openssl enc -aes-256-ctr -pass pass:"$1" -nosalt </dev/zero 2>/dev/null
}

ipfs_test()
{
    local url="http://$1:${PORT}/${PATHADDR}/$2";
    python3 run-test-old.py \
            --simple "Tye" \
            --url "$url" \
            --name "INTERNET3_IPFS_${MPDPOLICY}_${SIGATURE}_SEQ_${SEQ}_BUF_${EXIST_BUF_SIZE}_CAP_${FRONTDELAY}_${FRONTRATE}_BACKRATE_${BACKDELAY}_${BACKRATE}" \
            --testcount ${RUN_TEST_COUNT} \
            $3 $4;
#            --skipexist "True";
}

export DOCKER_NETWORK=ipfs-raw-network;
export SECOND_DOCKER_NETWORK=ipfs-host-network;
export IPFS_ABR_BASE=/mnt/d_drive/ipfs-abr-test;

export EXIST_BUF_SIZE_LIST=(0 3 6 9);

RANDOM=1357911; # set seed

export PATHADDR="ipfs/bafybeidnr2s7ubwwxjihi3lyxi6mcjhevl23cird6mcy4jrikbu3ouxrxq";
export PATHADDR="ipfs/bafybeibsf3d7wcywlzws2i7iol62yqm47e4djvs4bcb5pgucsoiunjqule";
export PATHADDR="ipfs/bafybeicmrns4l23a4ungvrdvvqxmhr7xxq4spyijaewl2yv7qops4kandm";
export PATHADDR="ipfs/bafybeiffucmp4u3k2owec5qwv65q4afkkrbftwfdtvp5wkvwm4us66klke";
#export PATHADDR="ipfs/bafybeibjn2z7hhf5d46zvbvoj5waqqte7qmifbn5hpdw4uu4gy6gip4k3q/ipfs-sunrise-video";
export STORAGE_HOST='/ip4/34.125.190.170/tcp/4001/p2p/12D3KooWMjf2Encxa2ZCiCeXZGu5hh12w9L4fHJr2NDHqhNLPMwM'
#export STORAGE_HOST='/ip4/139.178.91.231/tcp/4001/p2p/12D3KooWAdxvJCV5KXZ6zveTJmnYGrSzAKuLUKZYkZssLk7UKv4i'
#export STORAGE_HOST='/ip4/139.178.91.227/tcp/4001/p2p/12D3KooWKhPb9tSnCqBswVfC5EPE7iSTXhbF4Ywwz2MKg5UCagbr'

RTT_ARRAY=(1ms);
RATE_ARRAY=(2500mbit);

BACKRTT_ARRAY=(1ms);
#EXIST_BUF_SIZE_ARRAY=(3)
BACKRATE_ARRAY=(2500mbit);
#BACKRATE_ARRAY=(25mbit 8mbit);

if [[ "$1" == "1" ]]; then
    export REPO=${IPFS_ABR_BASE}/ipfs-mount1;
elif [[ "$1" == "2" ]]; then
    export REPO=${IPFS_ABR_BASE}/ipfs-mount2;
elif [[ "$1" == "3" ]]; then
    export REPO=${IPFS_ABR_BASE}/ipfs-mount3;
elif [[ "$1" == "4" ]]; then
    export REPO=${IPFS_ABR_BASE}/ipfs-mount4;
elif [[ "$1" == "5" ]]; then
    export REPO=${IPFS_ABR_BASE}/ipfs-mount5;
fi

RUN_TEST_COUNT=1;
SEQ_TEST_COUNT=3;

MPDPOLICY_LIST=(UNCHANGE UNIFORM);

for plcy in ${MPDPOLICY_LIST[@]}; do
    export MPDPOLICY="$plcy";
    for e in ${EXIST_BUF_SIZE_LIST[@]}; do
        export EXIST_BUF_SIZE="$e";

        if [[ "$EXIST_BUF_SIZE" == "0" ]]; then
            export PRESET_BUFLEVEL=();
        elif [[ "$EXIST_BUF_SIZE" == "3" ]]; then
            export PRESET_BUFLEVEL=(3 6 9);
        elif [[ "$EXIST_BUF_SIZE" == "6" ]]; then
            export PRESET_BUFLEVEL=(1 3 5 7 9 11);
        elif [[ "$EXIST_BUF_SIZE" == "9" ]]; then
            export PRESET_BUFLEVEL=(1 3 4 5 6 7 8 9 11);
        fi

        for rate in ${RATE_ARRAY[@]}; do
            for rtt in ${RTT_ARRAY[@]}; do
                for backrtt in ${BACKRTT_ARRAY[@]}; do
                    for backrate in ${BACKRATE_ARRAY[@]}; do
                        export FRONTDELAY="$rtt";
                        export FRONTRATE="$rate";
                        export BACKDELAY="$backrtt";
                        export BACKRATE="$backrate";

                        export PORT="7080";
                        for S in $(seq 1 $SEQ_TEST_COUNT); do
                            export SEQ=$S;
                            testpf second_10min_4k_dash.html;
                        done
                    done
                done
            done
        done
    done
done
