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

# Specify vagrant_vm_box in settings.yaml
puts("Loading settings.yaml...")
if not File.exist?("settings.yaml")
  puts("settings.yaml not found, using settings.yaml.example instead. Please create a settings.yaml from settings.yaml.example if you want to use custom vagrant settings.")
  SETTINGS_YAML = YAML.load_file("settings.yaml.example")
else
  SETTINGS_YAML = YAML.load_file("settings.yaml")
end

VM_BOX = SETTINGS_YAML['vagrant_vm_box']
DEFAULT_BOX_OPTS = SETTINGS_YAML['default_box_opts']
ALL_BOX_OPTS = SETTINGS_YAML['vagrant_box_opts']

if not ALL_BOX_OPTS.has_key?(VM_BOX)
  abort("ERROR: vagrant_vm_box: #{VM_BOX} not in vagrant_box_opts, please check your settings.yaml")
end
BOX_OPTS = ALL_BOX_OPTS[VM_BOX]

# Before we provision, change Hiera's :datadir:
# We use a separate file `.vagrant_hiera.yaml` to avoid race conditions when
# editing `hiera.yaml` directly (Vagrantfile is not procedural)
puts("Creating .vagrant_hiera.yaml...")
HIERA_YAML = YAML.load_file("hiera.yaml")
HIERA_YAML[:yaml][:datadir] = BOX_OPTS["hiera_datadir"]
IO.write(".vagrant_hiera.yaml", HIERA_YAML.to_yaml)

# Start the Vagrant process
Vagrant.configure(2) do |config|
  config.vm.box = VM_BOX
  config.vm.provider "virtualbox" do |v|
    # use default values if not overwritten
    v.memory = BOX_OPTS.has_key?("memory") ? BOX_OPTS["memory"] : DEFAULT_BOX_OPTS["memory"]
    v.cpus = BOX_OPTS.has_key?("cpus") ? BOX_OPTS["cpus"] : DEFAULT_BOX_OPTS["cpus"]
  end

  if File.exist?("/etc/profile.d/proxy.sh")
    # If the host machine has a proxy.sh, we're going to need one too.
    # This is done in two provisioning steps, because the "file" provisioner
    # runs as "vagrant" and we want the file to go in /etc/profile.d, which
    # "vagrant" can't write to.
    config.vm.provision "file", source: "/etc/profile.d/proxy.sh", destination: "~/.proxyconf"
    config.vm.provision "shell", inline: "cp /home/vagrant/.proxyconf /etc/profile.d/proxy.sh"
  end

  # Shell Provisioner: Puppet configuration
  config.vm.provision "shell", path: BOX_OPTS["shell_provision_script"]

  # Mount .facts (used by Jenkins) at /etc/facter/facts.d
  config.vm.synced_folder ".facts", "/etc/facter/facts.d"
  # Sync extra folders (if specified)
  if BOX_OPTS.has_key?('synced_folders')
    BOX_OPTS['synced_folders'].each do |synced_folder|
      config.vm.synced_folder synced_folder["src"], synced_folder["dest"]
    end
  end

  # Puppet Provisioner
  # Runs Puppet via 'puppet apply' locally
  config.vm.provision "puppet" do |puppet|
    puppet.manifest_file = "site.pp"
    puppet.hiera_config_path = ".vagrant_hiera.yaml"
    puppet.working_directory = "/tmp/vagrant-puppet"
    puppet.module_path = "modules"
    puppet.facter = {
      "vagrant" => "1",
    }
    puppet.options = "--verbose --detailed-exitcodes --trusted_node_data --no-stringify_facts"
  end
end
