# frozen_string_literal: true

# Alojamiento local, solo genera el sitio, con lo que no necesita hacer
# nada más
class DeployLocal < Deploy
  store :values, accessors: %i[], coder: JSON

  before_destroy :remove_destination!

  # Realizamos la construcción del sitio usando Jekyll y un entorno
  # limpio para no pasarle secretos
  #
  # Pasamos variables de entorno mínimas para no filtrar secretos de
  # Sutty
  def deploy
    return false unless mkdir
    return false unless yarn
    return false unless bundle

    jekyll_build
  end

  # Sólo permitimos un deploy local
  def limit
    1
  end

  # Obtener el tamaño de todos los archivos y directorios (los
  # directorios son archivos :)
  def size
    @size ||= begin
      paths = [destination, File.join(destination, '**', '**')]

      Dir.glob(paths).map do |file|
        if File.symlink? file
          0
        else
          File.size(file)
        end
      end.inject(:+)
    end
  end

  def destination
    File.join(Rails.root, '_deploy', site.hostname)
  end

  private

  def mkdir
    FileUtils.mkdir_p destination
  end

  # Un entorno que solo tiene lo que necesitamos
  def env
    # XXX: This doesn't support Windows paths :B
    paths = [File.dirname(`which bundle`), '/usr/bin', '/bin']

    {
      'HOME' => home_dir,
      'PATH' => paths.join(':'),
      'SPREE_API_KEY' => site.tienda_api_key,
      'SPREE_URL' => site.tienda_url,
      'AIRBRAKE_PROJECT_ID' => site.id.to_s,
      'AIRBRAKE_PROJECT_KEY' => site.airbrake_api_key,
      'JEKYLL_ENV' => Rails.env,
      'LANG' => ENV['LANG'],
      'YARN_CACHE_FOLDER' => yarn_cache_dir
    }
  end

  def yarn_cache_dir
    Rails.root.join('_yarn_cache').to_s
  end

  def yarn_lock
    File.join(site.path, 'yarn.lock')
  end

  def yarn_lock?
    File.exist? yarn_lock
  end

  def gem
    run %(gem install bundler --no-document)
  end

  # Corre yarn dentro del repositorio
  def yarn
    return true unless yarn_lock?

    run 'yarn install --production'
  end

  def bundle
    if Rails.env.production?
      run %(bundle install --no-cache --path="#{gems_dir}")
    else
      run %(bundle install)
    end
  end

  def jekyll_build
    run %(bundle exec jekyll build --trace --profile --destination "#{escaped_destination}")
  end

  # no debería haber espacios ni caracteres especiales, pero por si
  # acaso...
  def escaped_destination
    Shellwords.escape destination
  end

  # Eliminar el destino si se elimina el deploy
  def remove_destination!
    FileUtils.rm_rf destination
  end
end