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

$cluster_domain = ENV["CLUSTER_DOMAIN"] || "demo.localflynn.com"
$flags_gui = ENV["FLAG_GUI"] || "false"
$flag_update = ENV["FLAG_UPDATE"] || "false"
$flag_bootstrap = ENV["FLAG_BOOTSTRAP"] || "true"

# Fail if Vagrant version is too old
begin
  Vagrant.require_version ">= 1.6.0"
rescue NoMethodError
  $stderr.puts "This Vagrantfile requires Vagrant version >= 1.6.0"
  exit 1
end

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "flynn-base"
  config.vm.box_url = "https://dl.flynn.io/vagrant/flynn-base.json"
  config.vm.box_version = "> 0"

  # RFC 5737 TEST-NET-1 used to avoid DNS rebind protection
  config.vm.network "private_network", ip: "192.0.2.200"

  config.vm.synced_folder ".", "/vagrant", disabled: true

  if Vagrant.has_plugin?("vagrant-vbguest")
    # vagrant-vbguest can cause the VM to not start: https://github.com/flynn/flynn/issues/2874
    config.vbguest.auto_update = false
  end

  config.vm.provider "virtualbox" do |v|
    v.memory = ENV["VAGRANT_MEMORY"] || 2048
    v.cpus = ENV["VAGRANT_CPUS"] || 2

    # Workaround for https://www.virtualbox.org/ticket/15705
    v.customize ["modifyvm", :id, "--cableconnected1", "on"]
  end

  config.vm.provider "vmware_fusion" do |v|
    v.vmx["memsize"] = ENV["VAGRANT_MEMORY"] || 2048
    v.vmx["numvcpus"] = ENV["VAGRANT_CPUS"] || 2
  end

  # Show VM GUI as a visual reminder that the VM is running
  if $flag_gui == "true"
    config.vm.provider "virtualbox" do |v|
      v.gui = true
    end
    config.vm.provider "vmware_fusion" do |v|
      v.gui = true
    end
  end

  # Provisioners
  if $flag_update == "true"
    config.vm.provision "shell", inline: <<-SCRIPT
      flynn-host download
    SCRIPT
  end
  if $flag_bootstrap == "true"
    config.vm.provision "shell", privileged: false, inline: <<-SCRIPT
      sudo systemctl enable flynn-host.service
      sudo systemctl start flynn-host.service
      export CLUSTER_DOMAIN="#{$cluster_domain}"
      flynn-host bootstrap 2>&1
    SCRIPT
  end
end
