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

# path to your application root.
APP_ROOT = File.expand_path('..', __dir__)

def system!(*args)
  system(*args) || abort("\n== Command #{args} failed ==")
end

FileUtils.chdir APP_ROOT do
  # This script is a way to setup or update your development environment automatically.
  # This script is idempotent, so that you can run it at anytime and get an expectable outcome.
  # Add necessary setup steps to this file.
  
  # we don't install dependencies on ci because it's been done already
  if ARGV.length == 0 || (ARGV.length > 0 && ARGV[0] != 'ci')
    puts '== Installing dependencies (Ruby) =='
    system! 'gem install bundler --conservative'
    system('bundle check') || system!('bundle install')

    puts "\n== Installing dependencies (JS) =="
    system!('yarn -s')
  end


  if ARGV.length == 0 || (ARGV.length > 0 && ARGV[0] != 'ci')
    puts "\n== Copying env file =="
    unless File.exist?('.env')
      FileUtils.cp '.env.template', '.env'
    end
    puts "\n== Create new secrets =="
    File.write('.env', File.read('.env').gsub(/-- secret string --/) { SecureRandom.hex(64) })
  else
    puts "\n== Copying env file =="
    FileUtils.cp '.env.test', '.env'
  end

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

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

  puts "\n== Restarting application server =="
  system! 'bin/rails restart'
end