#!/bin/bash

# Compute V8 memory flags based on hardware capabilities.
# Output is space-separated flags; systemd ExecStart relies on word splitting.
#
# --v8-pool-size: based on CPU core count (background compilation + GC threads)
# --max-semi-space-size: based on available RAM (young generation memory)

core_count=$(nproc)
mem_gb=$(awk '/MemTotal/ {printf "%.0f", $2 / 1024 / 1024}' /proc/meminfo)

# v8-pool-size: scale with cores, cap at 16
if [[ "$core_count" -ge 16 ]]; then
  pool_size=16
elif [[ "$core_count" -ge 4 ]]; then
  pool_size=$core_count
else
  pool_size=4
fi

# max-semi-space-size: scale with available RAM, omit for large devices (let V8 auto-tune)
if [[ "$mem_gb" -ge 32 ]]; then
  semi_flag=""
elif [[ "$mem_gb" -ge 8 ]]; then
  semi_flag="--max-semi-space-size=16"
elif [[ "$mem_gb" -ge 4 ]]; then
  semi_flag="--max-semi-space-size=12"
else
  semi_flag="--max-semi-space-size=8"
fi

echo "${semi_flag:+${semi_flag} }--v8-pool-size=${pool_size}"
