# SPDX-FileCopyrightText: 2015-2023 Alexey Rochev
#
# SPDX-License-Identifier: CC0-1.0

require "etc"

def get_cpus
  cpus = Etc.nprocessors
  puts "VM CPUs: #{cpus}"
  cpus
end

def get_memory
  command = ["sysctl", "-n", "hw.memsize"]
  memsize_bytes = IO.popen(command) { |io| io.read.strip.to_i }
  raise "Failed to run #{command}: #{$?}" unless $?.exitstatus == 0
  raise "Total system memory is unknown" unless memsize_bytes > 0
  memsize_mibs = memsize_bytes / 1048576
  puts "Total system memory is #{memsize_mibs} MiB"
  vm_memory = memsize_mibs - 1024
  if vm_memory < 1024
    vm_memory = 1024
  end
  puts "VM memory: #{vm_memory} MiB"
  vm_memory
end

raise "This Vagrantfile can be used only on macOS" unless Etc.uname[:sysname] == "Darwin"

Vagrant.configure("2") do |config|
  config.vm.box = "generic/freebsd#{ENV["FREEBSD_VERSION"]}"
  config.vm.synced_folder ".", "/vagrant", type: "rsync"
  config.vm.synced_folder ENV["GITHUB_WORKSPACE"], "/workspace", type: "rsync"
  config.vm.provider "virtualbox" do |v|
    v.cpus = get_cpus
    v.memory = get_memory
  end
end
