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

Vagrant.configure("2") do |config|

  config.vm.box = 'debian/jessie64'
  config.vm.host_name = 'postgresql'

  config.vm.provider "virtualbox" do |v|
    v.customize ["modifyvm", :id, "--memory", 512]
  end

  config.vm.network "forwarded_port", guest: 5432, host: 15432

  config.vm.provision "shell", privileged: true, inline: <<-SHELL
    APP_DB_USER=coin
    APP_DB_NAME=coin
    APP_DB_PASS=coin

    PG_VERSION=9.4
    PG_CONF="/etc/postgresql/$PG_VERSION/main/postgresql.conf"
    PG_HBA="/etc/postgresql/$PG_VERSION/main/pg_hba.conf"

    apt-get -y update
    apt-get install -y postgresql

    # Edit postgresql.conf to change listen address to '*':
    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/" "$PG_CONF"

    # Append to pg_hba.conf to add password auth:
    echo "host    all             all             all                     md5" >> "$PG_HBA"

    cat << EOF | su - postgres -c psql
    -- Cleanup, if required
    DROP DATABASE IF EXISTS $APP_DB_NAME;
    DROP USER IF EXISTS $APP_DB_USER;

    -- Create the database user:
    CREATE USER $APP_DB_USER WITH PASSWORD '$APP_DB_PASS';
    -- Allow db creation (usefull for unit testing)
    ALTER USER $APP_DB_USER CREATEDB;

    -- Create the database:
    CREATE DATABASE $APP_DB_NAME WITH OWNER=$APP_DB_USER
                                  LC_COLLATE='en_US.utf8'
                                  LC_CTYPE='en_US.utf8'
                                  ENCODING='UTF8'
                                  TEMPLATE=template0;
EOF

    systemctl restart postgresql
    SHELL
end