# -*- mode: ruby -*-
# vi: set ft=ruby :

def env_or_default(key, value)
  if ENV.key?(key) then
    return ENV[key]
  else
    return value
  end
end

# Read parameters from the environment.
vm_cpus           = env_or_default("VM_CPU", 4)
vm_memory         = env_or_default("VM_MEMORY", 16 * 1024)
# More parameters from the environment. These are only used during provisioning.
apt_proxy         = env_or_default("APT_PROXY", "")
vm_locale         = env_or_default("VM_LOCALE", "en_GB.UTF-8")
chezmoi_source    = env_or_default("CHEZMOI_SOURCE", "")
vmnet_back_addr   = env_or_default("VMNET_BACK_ADDR", "10.0.0.1")
vmnet_front_addr  = env_or_default("VMNET_FRONT_ADDR", "10.0.1.1")
vmnet_domain      = env_or_default("VMNET_DOMAIN", "envdev.test")
vmnet_bind_key_id = env_or_default("VMNET_BIND_KEY_ID", "terraform.#{vmnet_domain}")
vmnet_bind_key    = env_or_default("VMNET_BIND_KEY", "")

Vagrant.configure("2") do |config|
  config.vagrant.plugins = ["vagrant-libvirt"]

  config.ssh.forward_agent = true
  config.ssh.forward_x11 = true

  config.vm.box = "generic/debian12"
  config.vm.hostname = "workvm"
  config.vm.box_check_update = false

  config.vm.provider "libvirt" do |lv|
    lv.memory = vm_memory
    lv.cpus = vm_cpus
    lv.graphics_type = "spice"
    lv.video_type = "virtio"
    lv.nested = true
    lv.disk_driver :discard => "unmap"
  end

  config.vm.provision "shell",
    reboot: true,
    inline: <<-EOF
      export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true;
      apt-get remove -y --purge resolvconf
    EOF
  config.vm.provision "shell",
    path: "scripts/00-network.sh",
    reboot: true,
    env: { "APT_PROXY" => apt_proxy }
  config.vm.provision "shell",
    path: "scripts/01-os-basics.sh",
    reboot: true
  config.vm.provision "file",
    source: "ansible",
    destination: "/var/cache/provision/playbook"
  config.vm.provision "shell",
    path: "scripts/02-provision.sh",
    reboot: true,
    privileged: false,
    env: {
      "VM_LOCALE"         => vm_locale,
      "CHEZMOI_SOURCE"    => chezmoi_source,
      "VMNET_BACK_ADDR"   => vmnet_back_addr,
      "VMNET_FRONT_ADDR"  => vmnet_front_addr,
      "VMNET_DOMAIN"      => vmnet_domain,
      "VMNET_BIND_KEY_ID" => vmnet_bind_key_id,
      "VMNET_BIND_KEY"    => vmnet_bind_key
    }

  config.vm.synced_folder '.', '/vagrant', :disabled => true
end