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

require 'fileutils'
require 'ipaddr'
require 'securerandom'
DISK_UUID = SecureRandom.urlsafe_base64(9)

$num_instances = (ENV['NODES'] || 3).to_i
$cpus = (ENV['CPUS'] || 2).to_i
$memory = (ENV['MEMORY'] || 4096).to_i
$disks = 2
$disk_size = "10G"
$box = "gmmaha/clearlinux"
$loader = File.join(File.dirname(__FILE__), "OVMF.fd")
$vm_name_prefix = "clr"
base_ip = IPAddr.new("192.52.100.10")
hosts = {}
proxy_ip_list = ""
#DISK_UUID = Time.now.utc.to_i
driveletters = ('a'..'z').to_a

if not File.exists?($loader)
  system('curl -O https://download.clearlinux.org/image/OVMF.fd')
end

# We need v 1.0.14 or above for this vagrantfile to work.
unless Vagrant.has_plugin?("vagrant-guests-clearlinux")
  system "vagrant plugin install vagrant-guests-clearlinux"
end

# Install plugins that you might need.
if ENV['http_proxy'] || ENV['HTTP_PROXY']
  system "vagrant plugin install vagrant-proxyconf" unless Vagrant.has_plugin?("vagrant-proxyconf")
end

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://vagrantcloud.com/search.
  config.vm.box = $box

  #Setup proxies for all machines
  (1..$num_instances).each do |i|
    base_ip = base_ip.succ
    hosts["clr-%02d" % i] = base_ip.to_s
  end

  hosts.each do |vm_name, ip|
    proxy_ip_list = ("#{proxy_ip_list},#{vm_name},#{ip}")
  end

  hosts.each do |vm_name, ip|
    config.vm.define vm_name do |c|
      c.vm.hostname = vm_name
      c.vm.network :private_network, ip: ip, autostart: true
      c.vm.provider :libvirt do |lv|
        lv.loader = $loader
        lv.cpu_mode = "host-passthrough"
        lv.nested = true
        lv.cpus = $cpus
        lv.memory = $memory
        (1..$disks).each do |d|
          lv.storage :file, :device => "hd#{driveletters[d]}", :path => "disk-#{vm_name}-#{d}-#{DISK_UUID}.disk", :size => $disk_size, :type => "raw"
        end
      end
      if Vagrant.has_plugin?("vagrant-proxyconf")
        c.proxy.http = (ENV['http_proxy']||ENV['HTTP_PROXY'])
        c.proxy.https = (ENV['https_proxy']||ENV['HTTPS_PROXY'])
        c.proxy.no_proxy =  (ENV['no_proxy']+"#{proxy_ip_list}" || ENV['NO_PROXY']+"#{proxy_ip_list}" || "localhost,127.0.0.1,172.16.10.10#{proxy_ip_list}")
      end
      # Bad hack for the vagrant libvirt boxes. WIll be removed once they are fixed.
      c.vm.provision "shell", privileged: false, inline: "sudo usermod --password vagrant root"

      c.vm.provision "shell", privileged: false, path: "setup_system.sh"
    end
  end
end
