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

REQUIRED_PLUGINS = %w(vagrant-libvirt)
exit unless REQUIRED_PLUGINS.all? do |plugin|
  Vagrant.has_plugin?(plugin) || (
    puts "The #{plugin} plugin is required. Please install it with:"
    puts "$ vagrant plugin install #{plugin}"
    false
  )
end

$provision = <<SCRIPT
# see SETUP.md for details

export RAILS_ENV=development
export NODE_ENV=development
export NODE_OPTIONS=--openssl-legacy-provider

echo '[treehouse-vagrant] install packages'
sudo pacman -Syu --noconfirm base-devel git libidn
sudo pacman -Syu --noconfirm ruby ruby-bundler ruby-irb redis postgresql yarn
git clone https://aur.archlinux.org/ruby-foreman.git
cd ruby-foreman
yes | sudo -u vagrant makepkg -si

# treehouse mastodon files are synced here
cd /vagrant

echo '[treehouse-vagrant] init database'
if [ -d "data/" ]; then rm -rf data/; fi
mkdir -p data/
pg_ctl -D data/postgres initdb -o '-U mastodon --auth-host=trust'
echo 'unix_socket_directories = .' >> data/postgres/postgresql.conf
pg_ctl -D data/postgres start --silent

echo '[treehouse-vagrant] start redis'
mkdir -p data/redis
redis-server ./redis-dev.conf

echo '[treehouse-vagrant] bundle install'
if [ -d "vendor/bundle/" ]; then rm -rf vendor/bundle/; fi
bundle config set --local path 'vendor/bundle/'
bundle install

echo '[treehouse-vagrant] yarn install'
yarn add webpack
git restore package.json yarn.lock
yarn install

echo '[treehouse-vagrant] bundle db'
bundle exec rake db:setup || exit

echo '[treehouse-vagrant] bundle assets'
bundle exec rake assets:precompile || exit

echo '[treehouse-vagrant] foreman start'
foreman start

SCRIPT

# TODO: allow `vagrant up`
#       this requires persistent storage
#       i.e., not saving data, assets, etc to /vagrant
#$start = <<SCRIPT
#
#export NODE_ENV=development
#export RAILS_ENV=development
#cd /vagrant
#pg_ctl -D data/postgres start --silent
#redis-server ./redis-dev.conf
#foreman start
#
#SCRIPT

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

  config.vagrant.plugins = "vagrant-libvirt"

  config.vm.box = "archlinux/archlinux"
  config.vm.hostname = "mastodon.local"

  # vagrant ssh -- -L 3000:localhost:3000  (:
  #config.vm.network :forwarded_port, guest: 3000, host: 3000

  config.vm.synced_folder ".", "/vagrant",
    type: "rsync",
    rsync__args: ["--verbose", "--archive", "--delete", "-z"],
    rsync__exclide: ".git/"

  config.vm.provision :shell, inline: $provision, privileged: false
  #config.vm.provision :shell, inline: $start, run: 'always', privileged: false

  config.vm.provider :libvirt do |libvirt|
    libvirt.driver = "kvm"
    libvirt.memory = 4096
    libvirt.cpus = 4
  end

end
