#!/usr/bin/env ruby

require "fileutils"

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

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

#
# Prints the log message with a yellow color to distinguish logs
# See more information here - https://stackoverflow.com/questions/1489183/how-can-i-use-ruby-to-colorize-the-text-output-to-a-terminal
#
def log(message, color: :yellow)
  color_code = if color == :yellow
                 "33"
               elsif color == :red
                 "31"
               else
                 "37"
               end

  printf "\033[1;#{color_code}m";

  puts "\n[ bin/setup ] #{message}"

  printf "\033[0m"
end


FileUtils.chdir APP_ROOT do
  log "---------------------"
  log "❤️  Setup started... ❤️"
  log "---------------------"

  log "Encountered any issues with setup?\nIf so, please open an issue @ https://github.com/rubyforgood/human-essentials/issues/new/choose", color: :red

  #
  # Validate that the ruby version requirement is met.
  #
  expected_ruby_version = `cat .ruby-version`.chomp
  current_ruby_version = `ruby -v`.chomp
  unless current_ruby_version.include?(expected_ruby_version)
    log "Ruby version must be #{expected_ruby_version}. You are on #{current_ruby_version}", color: :red
    exit
  end

  log "== Installing dependencies =="
  system! "gem install foreman"
  system! "gem install bundler --conservative"
  system!("bundle update --bundler --verbose")
  system!("bundle check") || system!("bundle install")

  unless File.exist?('.env')
    log "== Setting up .env file from .env.example =="
    system!('cp .env.example .env')
    log  "Check .env to see if your database credentials are correct.\nPress Enter to continue...", color: :red
    gets
  end

  log "== Preparing database =="
  log "⚠️  If you use docker to run postgres, make sure your database is running ⚠️"
  system! 'bin/rails db:reset'
  system! 'bin/rails db:test:prepare'

  log "== Removing old logs, tempfiles, and jobs =="
  system! 'bin/rails log:clear tmp:clear jobs:clear'

  log "== Restarting application server =="
  system! 'bin/rails restart'

  log "== Precompiling assets =="
  system! 'bin/rails assets:precompile'

  log "---------------------"
  log "❤️  Done! Run bin/start to run the application locally at http://localhost:3000 ❤️"
  log "[Note] It may take up to 5-10 seconds for the styles to compile, refresh after 10 seconds if the styles are looking unusual.", color: :red
  log "---------------------"
end
