#!/bin/bash
set -ueo pipefail

echo JAVA_HOME=$JAVA_HOME
export PATH=$JAVA_HOME/bin:$PATH
echo PATH=$PATH

# TODO: filter out cgroupsv2 mounts (will have cgroup2 in type field)
cgroot="$(awk '/cgroup.*memory/ { print $5 }' /proc/self/mountinfo)"
cgproc="$(awk -F: '/memory/ { print $3 }' /proc/self/cgroup)"
cd "$cgroot/$cgproc"
pwd

# create a new cgroup, underneath the current one
tempcg="$(mktemp -d -p "$PWD" cgtest.XXXXXX)"
echo "$tempcg"
cleanup()
{
    sleep 1
    echo $$ > "$tempcg/../tasks"
    rmdir "$tempcg"
}
trap cleanup INT EXIT

# establish real system memory (in kB), and a bad value for the limit (in bytes)
realmem="$(awk '/MemTotal.*kB$/ { print $2 }' /proc/meminfo)"
badmem=$(($realmem * 2 * 1024))
echo "realmem = $realmem (kiB)"
echo "badmem = $badmem (bytes)"

# move into the new cgroup and set a memory limit higher than available RAM
echo $$ > "$tempcg/tasks"
echo "setting memory limit to ${badmem}"
echo "${badmem}" > "$tempcg/memory.limit_in_bytes"
# ensure it set XXX sanity check value
if [ $(cat "$tempcg/memory.limit_in_bytes") -ne "$badmem" ]; then
    echo "failed to set bad cgroup memory limit"
    exit 1
fi

# Setting InitialRAMPercentage=25 means InitialHeapSize should be 25% of realmem, not badmem
initialHeap="$(java -Xlog:os+container=trace -XX:+PrintFlagsFinal -XX:InitialRAMPercentage=25.0 -version \
	| tee /dev/stderr \
	| awk '/InitialHeapSize/ { print $4 }')"

# value should be < (realmem / 2 == badmem / 4)
# (what about rounding?)
goodheap=$(($realmem * 1024 / 4))
if [ "$initialHeap" -ge "$goodheap" ]; then
	echo "incorrect initialHeap $initialHeap > $goodheap" >&2
	exit 1
fi
