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

include FileUtils

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

# if relative url root not set, use default for this app
ENV['RAILS_RELATIVE_URL_ROOT'] ||= "/pun/sys/myjobs" if ENV['RAILS_ENV'] == 'production'

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

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

  def production?
    env == "production"
  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 = "job-composer"

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

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== Building My Jobs 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"

  if APP.production?
    puts "\n== Compiling assets =="
    system! "bin/rake assets:clobber"
    system! "bin/rake assets:precompile"
  end

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

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