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

Vagrant.require_version ">= 2.0.0"

# Note: Cilium version must remain pinned to a v1.4 branch version.
#
# We do not have binary packages for iproute2 with BPF templating support
# so if we change this version without otherwise providing those packages
# then this GSG VM will break!
cilium_version = (ENV['CILIUM_VERSION'] || "v1.4.1")
cilium_opts = (ENV['CILIUM_OPTS'] || "--kvstore consul --kvstore-opt consul.address=127.0.0.1:8500 -t vxlan")
cilium_tag = (ENV['CILIUM_TAG'] || "v1.4.1")

# This runs only once when vagrant box is provisioned for the first time
$bootstrap = <<SCRIPT
# install docker-compose
curl -sS -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

# install cilium client
curl -sS -L "http://releases.cilium.io/#{cilium_version}/cilium-x86_64" -o /usr/local/bin/cilium
chmod +x /usr/local/bin/cilium

# Store specified tag and options for docker-compose so we can rerun easily
cat > /home/vagrant/cilium/examples/getting-started/.env <<EOF
CILIUM_TAG=#{cilium_tag}
CILIUM_OPTS=#{cilium_opts}
EOF

# cd into getting-started directory by default
echo 'cd ~/cilium/examples/getting-started' >> /home/vagrant/.bashrc
SCRIPT

# This is run every time vagrant box is booted
$run = <<SCRIPT
sudo mount bpffs /sys/fs/bpf -t bpf
cd ~/cilium/examples/getting-started
sudo -E docker-compose up -d --remove-orphans
SCRIPT

Vagrant.configure(2) do |config|
    config.vm.box = "bento/ubuntu-18.04"

    # 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

    config.vm.synced_folder "../..", "/home/vagrant/cilium", disabled: false

    config.vm.provider "virtualbox" do |vb|
        # Do not inherit DNS server from host, use proxy
        vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
        vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
        vb.memory = 2048
    end

    # install docker runtime
    config.vm.provision :docker, images: [
	"consul:0.8.3",
	"cilium/cilium:#{cilium_tag}"
    ]

    config.vm.provision "bootstrap", type: "shell", inline: $bootstrap
    config.vm.provision "run", type: "shell", run: "always",
       env: {"CILIUM_TAG" => cilium_tag, "CILIUM_OPTS" => cilium_opts},
       privileged: false, inline: $run

end
