#!/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')

# set max old space size to a fifth of system memory
osmem_kb=$( grep MemTotal /proc/meminfo | awk '{print $2}' )
fifth_osmem_kb=$(( osmem_kb / 5 ))
to_mb=$(( fifth_osmem_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
