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

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.hostname = "qinling"

  config.vm.network "private_network", ip: "192.168.33.18"
  config.vm.network "forwarded_port", guest: 7070, host: 7070

  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
    vb.customize ["modifyvm", :id, "--cpus", "1"]
    vb.gui = false
  end

  config.vm.provision "shell", privileged: false, inline: <<-SHELL

    #!/usr/bin/env bash
    sudo apt-get update
    sudo apt-get -y upgrade
    sudo apt-get -y install python-dev python-setuptools libffi-dev \
      libxslt1-dev libxml2-dev libyaml-dev libssl-dev rabbitmq-server git

    # Install mysql and initialize database.
    echo mysql-server-5.5 mysql-server/root_password password password | sudo debconf-set-selections
    echo mysql-server-5.5 mysql-server/root_password_again password password | sudo debconf-set-selections
    echo mysql-server-5.5 mysql-server/start_on_boot boolean true | sudo debconf-set-selections

    sudo apt-get -y install mysql-server python-mysqldb
    sudo sed -i 's/127.0.0.1/0.0.0.0/g' /etc/mysql/my.cnf
    sudo sed -i '44 i skip-name-resolve' /etc/mysql/my.cnf
    sudo service mysql restart

    HOSTNAME="127.0.0.1"
    PORT="3306"
    USERNAME="root"
    PASSWORD="password"
    DBNAME="qinling"
    create_db_sql="create database IF NOT EXISTS ${DBNAME}"
    mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} -e "${create_db_sql}"

    # Change rabbitmq credential.
    sudo rabbitmqctl change_password guest password

    # Install pip.
    curl -O https://bootstrap.pypa.io/get-pip.py && sudo python get-pip.py
    sudo pip install httpie

    # Install Qinling.
    git clone https://github.com/LingxianKong/qinling.git
    cd qinling
    sudo pip install -e .
    cd ..

    # Install python-qinlingclient
    git clone https://github.com/LingxianKong/python-qinlingclient.git
    cd python-qinlingclient
    sudo pip install -e .
    cd ..

    # Initialize Qinling configuration.
    sudo mkdir -p /vagrant/etc/qinling
    sudo mkdir -p /vagrant/log
    sudo mkdir -p /opt/qinling/function
    sudo chown ubuntu:ubuntu /opt/qinling/function
    cp /vagrant/qinling.conf.sample /vagrant/etc/qinling/qinling.conf

    # Qinling db migration.
    qinling-db-manage --config-file /vagrant/etc/qinling/qinling.conf upgrade head

    # Start Qinling service.
    qinling-server --server api,engine --config-file /vagrant/etc/qinling/qinling.conf &

  SHELL
end
