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

require 'fileutils'
require 'ipaddr'
require 'securerandom'

$num_instances = (ENV['NODES'] || 3).to_i
$cpus = (ENV['CPUS'] || 4).to_i
$memory = (ENV['MEMORY'] || 8192).to_i
$disks = 2
# Using folder prefix instead of uuid until vagrant-libvirt fixes disk cleanup
$disk_prefix = File.basename(File.dirname(__FILE__), "/")
$disk_size = "10G"
$box = "AntonioMeireles/ClearLinux"
$box_ver = (ENV['CLEAR_VBOX_VER'])
File.exists?("/usr/share/qemu/OVMF.fd") ? $loader = "/usr/share/qemu/OVMF.fd" : $loader = File.join(File.dirname(__FILE__), "OVMF.fd")
$vm_name_prefix = "clr"
$base_ip = IPAddr.new("10.10.100.10")
$hosts = {}
$proxy_ip_list = "192.168.121.0/24"
$driveletters = ('a'..'z').to_a
$setup_fc = true ? (['true', '1'].include? ENV['SETUP_FC'].to_s) : false
$runner = ENV.has_key?('RUNNER') ? ENV['RUNNER'].to_s : "crio".to_s
$high_pod_count = ENV.has_key?('HIGH_POD_COUNT') ? ENV['HIGH_POD_COUNT'].to_s : ""
$CLRK8S_CLR_VER = ENV.has_key?('CLRK8S_CLR_VER') ? ENV['CLRK8S_CLR_VER'].to_s : ""
if !(["crio","containerd"].include? $runner)
  abort("it's either crio or containerd. Cannot do anything else")
end

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
  config.vm.box_version = $box_ver

  # Mount the current dir at home folder instead of default
  config.vm.synced_folder './', '/vagrant', disabled: true
  config.vm.synced_folder './', '/home/clear/' + File.basename(Dir.getwd), type: 'rsync',
    rsync__args: ["--verbose", "--archive", "--delete", "-zz", "--copy-links"]
  #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.cpu_mode = "host-passthrough"
        lv.nested = true
        lv.loader = $loader
        lv.cpus = $cpus
        lv.memory = $memory
        lv.machine_virtual_size = 40
        (1..$disks).each do |d|
          lv.storage :file, :device => "hd#{$driveletters[d]}", :path => "disk-#{$disk_prefix}-#{vm_name}-#{d}.disk", :size => $disk_size, :type => "raw"
        end
      end
      if ENV['http_proxy'] || ENV['HTTP_PROXY']
        if Vagrant.has_plugin?("vagrant-proxyconf")
          c.proxy.http = (ENV['http_proxy']||ENV['HTTP_PROXY'])
          c.proxy.https = (ENV['https_proxy']||ENV['HTTPS_PROXY'])
          if ENV['no_proxy'] || ENV['NO_PROXY']
            if ENV['no_proxy']
              c.proxy.no_proxy =  (ENV['no_proxy']+","+"#{$proxy_ip_list}")
            else
              c.proxy.no_proxy =  (ENV['NO_PROXY']+","+"#{$proxy_ip_list}")
            end
          else
            c.proxy.no_proxy =  "localhost,127.0.0.1,172.16.10.10,#{$proxy_ip_list}"
          end
        end
      end
      c.vm.provider :virtualbox do |_, override|
        override.vm.provision "shell", privileged: true, inline: "sudo mkdir -p /etc/profile.d; echo export MASTER_IP=#{$hosts["clr-01"]} > /etc/profile.d/cnsetup.sh"
      end
      c.vm.provision "shell", privileged: false, path: "setup_system.sh", env: {"RUNNER" => $runner, "HIGH_POD_COUNT" => $high_pod_count, "CLRK8S_CLR_VER" => $CLRK8S_CLR_VER}
      if $setup_fc
        if $runner == "crio".to_s
        c.vm.provision "shell", privileged: false, path: "setup_kata_firecracker.sh"
        else
        # Wish we could use device mapper snapshotter with containerd, but it
        # does not exist on any released containerd version. Failing for now
        # when we use FC with containerd
        abort("Cannot use containerd with FC for now.")
        #c.vm.provision "shell", privileged: false, path: "containerd_devmapper_setup.sh"
        end
      end
      # Include shells bundle to get bash completion and add kubectl's commands to vagrant's shell
      c.vm.provision "shell", privileged: false, inline: 'sudo -E swupd bundle-add shells; echo "source <(kubectl completion bash)" >> $HOME/.bashrc'
    end
  end
end
