#!/usr/bin/env ruby
# frozen_string_literal: true

VERSION = '9.3.4'
LINUX   = RbConfig::CONFIG['host_os'].include?('linux')
HOST    = '0.0.0.0'
PORT    = '8000'

require_relative '../lib/optimist'
require_relative '../apps/index'
apps = PagyApps::INDEX
opts = Optimist.options do
  text <<~HEAD
    Pagy #{VERSION} (https://ddnexus.github.io/pagy/playground)
    Playground to showcase, clone and develop pagy APPs
    APPs
    #{ apps.map do |name, path|
         "  #{name}#{' ' * (27 - name.length)}#{File.readlines(path)[3].sub('#    ', '').strip}"
       end.join("\n")
     }
    USAGE
      pagy APP [options]         Showcase APP from the installed gem
      pagy clone APP             Clone APP to the current dir
      pagy APPFILE [options]     Develop APPFILE from local path
    EXAMPLES
      pagy demo                  Showcase demo at http://#{HOST}:#{PORT}
      pagy clone repro           Clone repro to ./repro.ru
      pagy ~/my-repro.ru         Develop ~/my-repro.ru at#{HOST}:#{PORT}
  HEAD
  text 'Rackup options'
  opt :env,     'Environment',                  default: 'development'
  opt :host,    'Host',                         default: HOST, short: :o
  opt :port,    'Port',                         default: PORT
  opt :install, 'Install bundle for users',     default: true
  if LINUX
    text 'Rerun options'
    opt :rerun, 'Enable rerun for development', default: true
    opt :clear, 'Clear screen before each rerun'
  end
  text 'Other options'
  opt :quiet,   'Quiet mode for development'
  version VERSION
end
Optimist.educate if ARGV.empty?

run_from_repo = File.exist?(File.expand_path('../pagy.gemspec', __dir__))

# Bundle
require 'bundler/inline'
require 'bundler'
Bundler.configure
gemfile(opts[:install]) do
  source 'https://rubygems.org'
  gem 'rackup'
  gem 'rerun' if LINUX
end

arg = ARGV.shift
if arg.eql?('clone')
  name = ARGV.shift
  Optimist.die("Expected APP to be in [#{apps.keys.join(', ')}]; got #{arg.inspect}") unless apps.key?(arg)
  if File.exist?(name)
    print "Do you want to overwrite the #{name.inspect} file? (y/n)> "
    answer = gets.chomp
    Optimist.die("#{name.inspect} file already present") unless answer.start_with?(/y/i)
  end
  require 'fileutils'
  FileUtils.cp(apps[arg], '.', verbose: true)
else
  if apps.key?(arg)  # showcase env
    opts[:env]   = 'showcase'
    opts[:rerun] = false
    opts[:quiet] = true
    # Avoid the creation of './tmp/local_secret.txt' for showcase env
    ENV['SECRET_KEY_BASE'] = 'absolute secret!' if arg.eql?('rails')
    file = apps[arg]
  else                   # development env
    file = arg
  end
  Optimist.die("#{file.inspect} app not found") unless File.exist?(file)
  # Run command
  gem_dir = File.expand_path('..', __dir__)
  rackup  = "rackup -I #{gem_dir}/lib -r pagy -o #{opts[:host]} -p #{opts[:port]} -E #{opts[:env]} #{file}"
  rackup << ' -q' if opts[:quiet]
  if opts[:rerun]
    name  = File.basename(file)
    dir   = File.dirname(file)
    rerun = if run_from_repo   # rerun app also when gem dir files change (for pagy devs)
              "rerun --name #{name} -d #{dir},#{gem_dir} -p **/*.{rb,js,css,scss,ru,yml}"
            else
              "rerun --name #{name} -d #{dir} -p #{name}" # rerun only when app.ru changes
            end
    rerun << ' -q' if opts[:quiet]
    rerun << ' -c' if opts[:clear]
    rerun << " -- #{rackup}"
  end
  exec("PAGY_INSTALL_BUNDLE='#{opts[:install]}' #{rerun || rackup}")
end
