# Copyright 2016 The Rook Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

VAGRANTFILE_API_VERSION = "2"

$channel = "alpha"
$nodes = 3
$new_discovery_url="https://discovery.etcd.io/new?size=1"
$node_disks = 3
$disk_size = 5

require_relative 'util.rb'
require 'open-uri'

if File.exists?('.discovery-token')
  token = IO.readlines(".discovery-token")[0..-1].join
else
  discovery_token = open($new_discovery_url).read
  File.open(".discovery-token", 'w') { |file| file.write("#{token}") }
end

private_build = false
if ENV["START_LOCAL_ROOKD"] == "1"
  private_build = true
end

if private_build
  aci_location = "/release/quay.io-rook-rookd-dev.aci"
  aci_options = "--insecure-options=image"
else
  aci_location = "quay.io/rook/rookd:latest"
  aci_options = ""
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  set_coreos_box(config, $channel)

  (0..($nodes - 1)).each do |i|
    config.vm.define name="rook%02d" % i, primary: (i == 0), autostart: (i == 0) do |node|
      node.vm.hostname = name
      node.vm.network "private_network", ip: "172.20.20.#{10+i}"

      if i == 0
        # forward the API service port on only the first machine
        node.vm.network "forwarded_port", guest: 8124, host: 8124
      end

      attach_volumes(node, $node_disks, $disk_size)

      if private_build
        # run locally built ACI files
        node.vm.synced_folder "../../release", "/release", id: "release", :nfs => true, :mount_options => ['nolock,vers=3,tcp']
      end

      node.vm.provision :cloud_config, :template => "cloud-config.yml.in",
        :subst => { 
            "%%discovery_token%%" => "#{discovery_token}", 
            "%%aci_location%%" => "#{aci_location}",
            "%%aci_options%%" => "#{aci_options}" 
        }
    end
  end
end
