#!/bin/bash

MEMORY_448_MB=448
MEMORY_1792_MB=1792
MEMORY_4096_MB=4096

OS_SYSID=$( ubnt-tools id | grep 'board.sysid' | awk -F'=' '{print $2}' )
IS_ENVR_CORE=$(echo "$OS_SYSID" | grep -E '0xda28')
# UDM SE, UDM Pro, UDM Pro SE, UCG Max, UCG Fiber: <=4GB RAM gateway consoles
IS_SMALL_GATEWAY_CONSOLE=$(echo "$OS_SYSID" | grep -E '0xea13|0xea15|0xea2c|0xa69a|0xa6a8')

# set max old space size to a fraction of system memory:
# 1/6 on small gateway consoles, 1/5 elsewhere
osmem_divisor=5
if [[ -n "$IS_SMALL_GATEWAY_CONSOLE" ]]; then
  osmem_divisor=6
fi

osmem_kb=$( grep MemTotal /proc/meminfo | awk '{print $2}' )
heap_kb=$(( osmem_kb / osmem_divisor ))
to_mb=$(( heap_kb / 1024 ))
mem_alignment=$(( to_mb / 4 * 4 ))

if [[ -n "$IS_ENVR_CORE" ]]; then
  echo "$MEMORY_4096_MB"
elif [[ "$mem_alignment" -gt "$MEMORY_1792_MB" ]]; then
  # 448 MB is the minimum
  # 1792 MB is the maximum
  echo "$MEMORY_1792_MB"
elif [[ "$mem_alignment" -lt "$MEMORY_448_MB" ]]; then
  echo "$MEMORY_448_MB"
else
  echo "$mem_alignment"
fi
