#!/usr/bin/env ruby
require "pathname"
require "fileutils"
require "rake"

include FileUtils

ENV["RAILS_ENV"]               ||= ENV["PASSENGER_APP_ENV"] || "development"
ENV["RAILS_RELATIVE_URL_ROOT"] ||= ENV["PASSENGER_BASE_URI"]

# force the default relative urls so that assets compile correctly.
if ENV['RAILS_ENV'] == 'development'
  ENV['RAILS_RELATIVE_URL_ROOT'] ||= "/pun/dev/dashboard"
else
  ENV['RAILS_RELATIVE_URL_ROOT'] ||= "/pun/sys/dashboard"
end

# define application object
class App
  attr_accessor :env, :url

  def initialize(env:, url:)
    @env    = env
    @url    = url
  end

  def production?
    env == "production"
  end

  def development?
    env == "development"
  end

  def test?
    env == "test"
  end
end

# set application settings
APP = App.new(
  env:    ENV["RAILS_ENV"],
  url:    ENV["RAILS_RELATIVE_URL_ROOT"],
)

# path to your application root.
APP_ROOT = Pathname.new File.expand_path("../../",  __FILE__)
APP_NAME = "dashboard"

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

CACHE = "#{ENV['HOME']}/.cache/yarn/ood-dashboard-app"

chdir APP_ROOT do
  # This script is a starting point to setup your application.
  # Add necessary setup steps to this file:

  puts "\n== Building Dashboard App =="
  puts "RAILS_ENV               = #{APP.env}"
  puts "RAILS_RELATIVE_URL_ROOT = #{APP.url    || "not set"}"

  puts "\n== Installing dependencies =="
  system! "bin/bundle check 1>/dev/null 2>&1 || bin/bundle install --jobs 4 --retry 2"

  puts "\n== Installing yarn =="
  system! "npm install --production --prefix tmp yarn"
  system! "tmp/node_modules/yarn/bin/yarn --production install --cache-folder #{CACHE}"

  puts "\n== Compiling assets =="
  system! "bin/rails assets:clobber"
  system! "bin/rails assets:precompile"

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

  puts "\n== Restarting application server =="
  touch "tmp/restart.txt"
  puts ""
end
