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

Vagrant.configure("2") do |config|
  # --- Network (two subnets) ------------------------------------------------
  # VirtualBox host-only defaults: 192.168.56.0/24
  # libvirt (vagrant-libvirt + network "vagrant-56"): typically 192.168.121.0/24
  # If your libvirt network uses another range, change ip_libvirt and use
  # inventory/vagrant_libvirt.yml (or edit subnet there to match).
  vm_settings = {
    box: "bento/ubuntu-24.04",
    memory: 2048,
    cpus: 4,
    machines: [
      { name: "vagrant-pihole-01", mac: "52:54:00:56:00:04",
        ip_virtualbox: "192.168.56.4", ip_libvirt: "192.168.121.4" },
      { name: "vagrant-pihole-02", mac: "52:54:00:56:00:05",
        ip_virtualbox: "192.168.56.5", ip_libvirt: "192.168.121.5" }
    ]
  }

  # --- PLUGINS ---------------------------------------------------------------

  if Vagrant.has_plugin?("vagrant-vbguest")
    config.vbguest.auto_update = false
  end

  # --- MACHINES --------------------------------------------------------------

  vm_settings[:machines].each do |machine|
    config.vm.define machine[:name] do |node|
      node.vm.hostname         = machine[:name]
      node.vm.box              = vm_settings[:box]
      node.vm.box_check_update = false

      node.vm.provider "virtualbox" do |v, o|
        v.memory = vm_settings[:memory]
        v.cpus   = vm_settings[:cpus]
        o.vm.network "private_network",
                     ip: machine[:ip_virtualbox],
                     netmask: "255.255.255.0",
                     auto_config: true
        v.customize ["modifyvm", :id, "--macaddress2", machine[:mac].delete(":")]
        v.customize ["modifyvm", :id, "--graphicscontroller", "vboxsvga"]
        v.customize ["modifyvm", :id, "--accelerate-3d", "off"]
        v.customize ["modifyvm", :id, "--vram", "32"]
      end

      if Vagrant.has_plugin?("vagrant-libvirt")
        node.vm.provider "libvirt" do |l, o|
          l.memory = vm_settings[:memory]
          l.cpus   = vm_settings[:cpus]
          l.driver = "kvm"
          o.vm.network "private_network",
                       ip: machine[:ip_libvirt],
                       netmask: "255.255.255.0",
                       auto_config: true,
                       libvirt__network_name: "vagrant-56",
                       libvirt__mac: machine[:mac],
                       libvirt__mgmt_network: "none"
        end
      end

      node.vm.provision "shell",
                        inline: "date | tee /etc/vagrant_provisioned_at && ip -4 addr show || true",
                        privileged: true

      node.trigger.after :destroy do |trigger|
        trigger.info = "Removing known_hosts entry for #{machine[:name]}"
        trigger.on_error = :continue
        trigger.run = { inline: "ssh-keygen -R #{machine[:name]}" }
      end
    end
  end
end
