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

# The calicoctl download URL.
calicoctl_url = "https://github.com/projectcalico/calico-containers/releases/download/v0.22.0/calicoctl"

# The version of the calico docker image to install.  This is used to pre-load
# the calico/node image which slows down the install process, but speeds up the
# tutorial.
#
# This version should match the version required by calicoctl installed from
# calicoctl_url.
calico_docker_ver = "v0.22.0"

# Size of the cluster created by Vagrant
num_instances=2

# Change basename of the VM
instance_name_prefix="calico"

# The IP address of the first server
primary_ip = "172.17.8.101"

Vagrant.configure(2) do |config|
  # always use Vagrants insecure key
  config.ssh.insert_key = false

  # Use an official Ubuntu base box
  config.vm.box = "ubuntu/trusty64"

  # Set up each box
  (1..num_instances).each do |i|
    vm_name = "%s-%02d" % [instance_name_prefix, i]
    config.vm.define vm_name do |host|
      host.vm.hostname = vm_name

      ip = "172.17.8.#{i+100}"
      host.vm.network :private_network, ip: ip

      # Fix stdin: is not a tty error (http://foo-o-rama.com/vagrant--stdin-is-not-a-tty--fix.html)
      config.vm.provision "fix-no-tty", type: "shell" do |s|
        s.privileged = false
        s.inline = "sudo sed -i '/tty/!s/mesg n/tty -s \\&\\& mesg n/' /root/.profile"
      end

      # The docker provisioner installs docker.
      host.vm.provision :docker, images: [
          "busybox:latest",
          "calico/node:#{calico_docker_ver}"
      ]

      # download calicoctl.
      host.vm.provision :shell, inline: "curl -L --silent #{calicoctl_url} -o /usr/local/bin/calicoctl"
      host.vm.provision :shell, inline: "chmod +x /usr/local/bin/calicoctl"

      # Calico uses etcd for clustering. Install it on the first host only.  We do not
      # auto-assign the name because the name may include the : of the Docker image
      # which will not be allowed.
      if i == 1
        host.vm.provision :docker do |d|
          d.run "quay.io/coreos/etcd:v3.0.3",
            args: "--net=host",
            auto_assign_name: false,
            cmd: "/usr/local/bin/etcd "\
                 "--advertise-client-urls http://#{primary_ip}:2379 "\
                 "--listen-client-urls http://0.0.0.0:2379 "
        end
      end

      # Ensure the vagrant and root users get the ETCD_AUTHORITY environment.
      host.vm.provision :shell, inline: %Q|echo 'export ETCD_AUTHORITY="#{primary_ip}:2379"' >> /home/vagrant/.profile|
      host.vm.provision :shell, inline: %Q|sudo sh -c 'echo "Defaults env_keep +=\"ETCD_AUTHORITY\"" >>/etc/sudoers'|
    end
  end
end
