#! /bin/sh

MEMCG_MOUNT=/dev/cgroups
MEMCG_LIMIT=60M
OOM_DISABLED=0
WRITE_OUT=/var/tmp/file
READ_IN=""

set -e

if [ $# -gt 0 ]
then
	MEMCG_LIMIT=$1
fi

if [ $# -gt 1 ]
then
	WRITE_OUT=$2
fi

if [ $# -gt 2 ]
then
	READ_IN=$3
fi


if [ ! -d $MEMCG_MOUNT ]
then
	mkdir $MEMCG_MOUNT
	mount -t cgroup -o memory none $MEMCG_MOUNT
fi

cname="$MEMCG_MOUNT/test.$$"
echo using Limit $MEMCG_LIMIT for group $name

[ ! -d $cname ] && mkdir $cname
echo $MEMCG_LIMIT > $cname/memory.limit_in_bytes
echo $OOM_DISABLED > $cname/memory.oom_control

sync
echo 3 > /proc/sys/vm/drop_caches
sleep 1s

echo $$ >> $cname/tasks

back_pid=0
for count in 1000; do
  dd if=/dev/zero of=$WRITE_OUT bs=1M count=$count 2>&1 | sed 's/^/write /' &
  back_pid=$!

  if [ ! -z "$READ_IN" ]
  then
	  dd if=$READ_IN of=/dev/null bs=1M count=$count 2>&1 | sed 's/^/read /'
  fi
  wait $back_pid
  rm $WRITE_OUT
done
