#!/bin/bash

# Test http interface of sheepfs for cache

. ./common

trap "_uninit; exit \$status" 0 1 2 3 15
_uninit()
{
	umount $STORE/sheepfs > /dev/null 2>&1
	rm -rf $STORE/sheepfs > /dev/null 2>&1
}

_need_to_be_root

which nginx > /dev/null || _notrun "Require nginx but it's not running"
pkill nginx > /dev/null
nginx -c `pwd`/nginx.conf

for i in `seq 0 5`; do
	_start_sheep $i "-r swift,port=800$i"
done

_wait_for_sheep 6

_cluster_format -c 4:2

curl -s -X PUT http://localhost/v1/sd -H 'Content-Length: 0'
curl -s -X PUT http://localhost/v1/sd/sheep -H 'Content-Length: 0'

for i in 4 19 97 137; do
    _random | dd iflag=fullblock of=$STORE/data$i bs=1M count=$i &> /dev/null
    dd if=$STORE/data$i 2> /dev/null | md5sum > $STORE/data$i.1
done

# upload the objects
for i in 4 19 97 137; do
	curl -s -T $STORE/data$i -X PUT http://localhost/v1/sd/sheep/data$i &
done
wait

# mount objects in sheepfs
mkdir -p $STORE/sheepfs
$SHEEPFS $STORE/sheepfs/

echo "localhost:83" > $STORE/sheepfs/http/address

# mount objects
for i in 4 19 97 137; do
	echo "/sd/sheep/data$i" > $STORE/sheepfs/http/object
done

# read objects with 'cat'
for i in 4 19 97 137; do
	cat $STORE/sheepfs/http/sd/sheep/data$i | md5sum > $STORE/data$i.2 &
done
wait

# read with recored-size of 10K to step over two caches should return 10K
offset=`echo "64 * 1024 / 10"|bc`
for i in 97 137; do
	dd if=$STORE/sheepfs/http/sd/sheep/data$i skip=$offset bs=10K count=1 2> /dev/null | md5sum > $STORE/data$i.5
	dd if=$STORE/data$i skip=$offset bs=10K count=1 2> /dev/null | md5sum > $STORE/data$i.6
	diff -u $STORE/data$i.5 $STORE/data$i.6
done

# read objects with 'dd'
for i in 4 19 97 137; do
	dd if=$STORE/sheepfs/http/sd/sheep/data$i bs=1345679 2> /dev/null | md5sum > $STORE/data$i.3 &
done
wait

for i in 4 19 97 137; do
	diff -u $STORE/data$i.1 $STORE/data$i.2
	diff -u $STORE/data$i.1 $STORE/data$i.3
done

# read same objects with many processes
for i in `seq 1 4`; do
	dd if=$STORE/sheepfs/http/sd/sheep/data137 bs=134567 2> /dev/null | md5sum > $STORE/data$i.4 &
done
wait

for i in `seq 1 4`; do
	diff -u $STORE/data137.1 $STORE/data$i.4
done

_vdi_list

status=0
