# -*- mode: ruby -*-
# vi: set ft=ruby :
require 'yaml'

hosts_config = YAML.load_file('provisioning/vagrant.yml')

ansible_groups = {
  "dev" => hosts_config.map { |n, conf| n},
  "all_groups:children" => ["dev"]
}

Vagrant.configure("2") do |config|
  hosts_config.each_with_index do |(node_name, node_config), index|
    config.vm.define node_name do |machine|
      machine.vm.box = "ubuntu/trusty64"
      machine.vm.hostname = "#{node_name}.<%= slugifiedAppName %>.com"
      # machine.vm.network :private_network, ip: node_config['ip']
      machine.vm.network :private_network, type: 'dhcp'

      # machine.vm.synced_folder ".", "/vagrant" # for Windows users
      machine.vm.synced_folder ".", "/vagrant", type: "nfs" # use nfs for better performance (OSX and Linux only)

      machine.ssh.forward_agent = true
      machine.ssh.insert_key = false

      node_config['ports'].each do |port|
        machine.vm.network :forwarded_port, 
          host: port['host'], 
          guest: port['guest'], 
          id: port['id']
      end

      if node_config["provider"] == "virtualbox"
        machine.vm.provider "virtualbox" do |v|
            v.memory = node_config['memory']
            v.cpus = node_config['cpus']
        end
      else
        raise '#{ node_config["provider"] } provider not supported'
      end

      node_config["groups"].each do |group|
        if ansible_groups[group].nil?
          ansible_groups[group] = [node_name]
        else
          ansible_groups[group] += [node_name]
        end
      end

      # provision machines with ansible
      if index == hosts_config.length - 1
        machine.vm.provision :ansible do |ansible|
          ansible.playbook = "provisioning/roles.yml"
          ansible.groups = ansible_groups
          # ansible.ask_vault_pass = true
          ansible.limit = 'all' # Disable default limit
        end
      end
    end
  end
end