#!/bin/bash

if [ -r /etc/default/obs-server ]
then
  source /etc/default/obs-server
else
  echo "ERROR: Could not read config file, exiting ..."
  exit 1
fi

[ ! -d /dev/hugetlbfs ] && mkdir /dev/hugetlbfs

if [ -z "$(findmnt /dev/hugetlbfs)" ]
then
  echo "Mounting hugetlbfs ..."
  if ! mount hugetlbfs /dev/hugetlbfs -t hugetlbfs
  then
    echo "ERROR: unable to mount hugetlbfs !"
    exit 1
  fi
fi

typeset -i target_hugep=$(( OBS_INSTANCE_MEMORY * OBS_WORKER_INSTANCES /2 ))

/usr/sbin/sysctl -qw vm.nr_hugepages=${target_hugep}

typeset -i current_hugep=$(/usr/sbin/sysctl -n vm.nr_hugepages)

typeset -i cpt=0

while [ ${current_hugep} -lt ${target_hugep} -a ${cpt} -lt 12 ]
do
  sleep 1
  ((cpt++))
  /usr/sbin/sysctl -qw vm.nr_hugepages=${target_hugep}
  echo "Retry ${cpt}: vm.nr_hugepages=${current_hugep}"
  current_hugep=$(/usr/sbin/sysctl -n vm.nr_hugepages)
done

if [ ${current_hugep} -lt ${target_hugep} ]
then
  echo "ERROR: was not able to reserve ${target_hugep} hugepages (only ${current_hugep})!"
  exit 1
fi
echo "${target_hugep} hugepages reserved."
