#!/usr/bin/env ruby
require 'fileutils'

APP_ROOT = File.expand_path('..', __dir__)

def system!(*args)
  system(*args, exception: true)
end

FileUtils.chdir APP_ROOT do
  # This script is a way to set up or update your development environment automatically.
  # This script is idempotent, so that you can run it at any time and get an expectable outcome.
  # Add necessary setup steps to this file.

  puts "\n== Enabling default add-ons =="
  unless File.exist?('Gemfile.plugins') || File.exist?('lib/dradis/pro.rb')
    FileUtils.cp 'Gemfile.plugins.template', 'Gemfile.plugins'
  end

  puts '== Installing dependencies =='
  system! 'gem install bundler --conservative'
  unless system('bundle check')
    system('bundle config set path \'vendor/bundle/\'')
    system!('bundle install')
  end

  puts "\n== Copying sample files =="
  unless File.exist?('config/database.yml')
    FileUtils.cp 'config/database.yml.template', 'config/database.yml'
  end

  unless File.exist?('config/smtp.yml')
    FileUtils.cp 'config/smtp.yml.template', 'config/smtp.yml'
  end

  puts "\n== Preparing templates folder =="
  unless Dir.exist?('templates')
    FileUtils.mkdir 'templates'
  end

  puts "\n== Preparing database =="
  system! 'bin/rails db:prepare'

  puts "\n== Removing old logs and tempfiles =="
  system! 'bin/rails log:clear tmp:clear'

  unless ARGV.include?('--skip-server')
    puts "\n== Starting development server =="
    STDOUT.flush # flush the output before exec(2) so that it displays
    exec 'bin/dev', '-p', '8080'
  end
end
