# frozen_string_literal: true

def maintenance!(enable: true)
  execute :pwd
  execute :drush, 'state:set', 'system.maintenance_mode', enable.to_s.upcase
end

# rubocop:disable Metrics/AbcSize
def composer_auth
  compjson = File.expand_path('../../../composer.json', File.dirname(__FILE__))
  composer = JSON.parse File.read(compjson)
  composer['repositories'].collect { |e| e['url'] }.each do |u|
    next unless u =~ /oauth2:/

    require 'uri'
    url = ::URI.parse u
    if url.user && url.password
      execute :composer, 'config', '--global', "http-basic.#{url.host}", url.user, url.password
    end
  end
end
# rubocop:enable Metrics/AbcSize

def cache_clear
  execute :drush, 'cache:rebuild'
end

def update_db(site = 'default')
  maintenance!
  execute :drush, 'updatedb', '-y', '--cache-clear', "--uri=http://#{site}" # , '--post-updates'
  cache_clear
end

def config_sync_dir(site = 'default')
  if File.exist?("../../../config/sync/#{site}")
    Pathname.new(File.expand_path("../../../config/sync/#{site}", File.dirname(__FILE__)))
  else
    Pathname.new(File.expand_path('../../../config/sync/', File.dirname(__FILE__)))
  end
end

def site_uuid(site = 'default')
  siteyml = config_sync_dir(site).join('system.site.yml')
  if siteyml.exist?
    YAML.load_file(siteyml.to_s)['uuid']
  else
    SecureRandom.uuid
  end
end

def lang_uuid(_lang, site = 'default')
  langyml = config_sync_dir(site).join('system.site.yml')

  if langyml.exist?
    YAML.load_file(langyml.to_s)['uuid']
  else
    SecureRandom.uuid
  end
end

def languages(_site = 'default')
  langs = config_sync_dir.glob('language.entity.*.yml').map do |f|
    f.basename.to_s.scan(/^language\.entity\.(.+?)\.yml/).flatten.first
  end.compact.map(&:to_sym).sort
  langs.find_all { |lang| !%i[zxx und en].include?(lang) }
end

def within_each_site(current: false, &block)
  fetch(:sites, %w[default]).each do |site|
    drs = current ? drupal_site_root(site) : current_path.join(fetch(:drupal_root)).join("sites/#{site}")
    $stderr.puts "Processing site #{drs}"
    within drs do
      yield(site)
    end
  end
end

def drupal_site_root(site = 'default')
  release_path.join(fetch(:drupal_root)).join("sites/#{site}")
end

def translations_dir
  release_path.join(fetch(:drupal_root)).join(fetch(:translations_path))
end

namespace :load do
  task :defaults do
    set :drupal_root, 'web'
    set :sites, %w[default]
    set :translations_path, 'translations'
  end
end

namespace :composer do
  task :install do
    on roles(:app) do
      within release_path do
        composer_auth
        stage = fetch(:stage).to_s
        devel_enabled = %w[demo dev].include?(stage) ? '--dev' : '--no-dev'
        execute :composer, 'install', '--no-progress', '--no-interaction', '--prefer-dist', devel_enabled
      end
    end
  end
end

# rubocop:disable Metrics/BlockLength
namespace :drupal do
  task :set_paths do
    SSHKit.config.command_map[:drupal] =
      "#{fetch(:php_path, '/usr/bin/php')} -d display_errors=1 -d memory_limit=-1 #{shared_path}/vendor/bin/drupal"
    # rubocop:disable Layout/LineLength
    SSHKit.config.command_map[:drush] = "#{shared_path}/vendor/bin/drush"
    # rubocop:enable Layout/LineLength
    SSHKit.config.command_map[:composer] = lambda {
      "#{fetch(:php_path, '/usr/bin/php')} -d memory_limit=-1 -d allow_url_fopen=1 #{release_path}/composer.phar"
    }
  end

  namespace :site do
    task :backup do
      on roles(:app) do
        within_each_site(current: true) do |site|
          execute :drush, 'eval', "--uri=http://#{site}", %{'backup_migrate_perform_backup("default_db", "private_files", []);'}
        end
      end
    end

    desc 'Setting up a brand new drupal instance based on the configs we have'
    task :setup do
      invoke 'deploy:check'
      invoke 'drupal:set_paths'
      invoke 'deploy:updating'
      invoke 'composer:install'

      on roles(:app) do
        within release_path.join(fetch(:drupal_root)) do
          execute :drush, 'site:install', "--root=#{release_path.join(fetch(:drupal_root))}", '--locale=hu',
                  '--account-name=csopadmin', '--account-mail=info@csopak.hu', '--site-mail=spam@csopak.hu', '-y',
                  '--existing-config'
          execute :drush, 'config:set', '-y', 'system.site', 'uuid', site_uuid
          languages.each do |lang|
            execute :drush, 'config:set', '-y', "language.entity.#{lang}", 'uuid', lang_uuid(lang)
          end
          execute :drush, 'config:import', "--root=#{release_path.join(fetch(:drupal_root))}", '-y'
          # languages.each do |lang|
          #   execute :drush, 'locale:import', "--root=#{release_path.join(fetch(:drupal_root))}", lang,
          #           release_path.join("translations/#{lang}.po"), '--override=all',
          #           '--type=customized'
          # end
        end
      end

      invoke 'deploy:publishing'
      invoke 'deploy:published'
      invoke 'deploy:finishing'
      invoke 'deploy:finished'
    end

    task :offline do
      on roles(:app) do
        within_each_site do |site|
          maintenance!
        end
      end
    end

    task :online do
      on roles(:app) do
        within_each_site do |site|
          # execute :drupal, 'site:maintenance', 'off'
          maintenance! enable: false
        end
      end
    end
  end

  task :update do
    on roles(:app) do
      within_each_site do |site|
        update_db site
        maintenance!
        execute :drush, 'config:import', "--root=#{release_path.join(fetch(:drupal_root))}", "--uri=http://#{site}", '-y'
        cache_clear

        languages.each do |lang|
          execute :drush, 'config:set', '-y', "language.entity.#{lang}", 'uuid', lang_uuid(lang, site), "--uri=http://#{site}"
        end

        execute :drush, 'config:import', "--root=#{release_path.join(fetch(:drupal_root))}", "--uri=http://#{site}", '-y'

        # # Detect config-split and do if there is any
        # if Pathname(File.dirname(__FILE__)).join('../../../config_prod').exist?
        #   confsplit_profile = "config_#{fetch(:stage).to_s[0..3]}"
        #   execute :drush, 'config-split:import', confsplit_profile, '-y'
        # end

        execute :drush,  'locale:check', "--uri=http://#{site}"
        execute :drush,  'locale:update', "--uri=http://#{site}"

        # execute :drush, 'locale:rebuild'

        # Detect multilingual site with custom translations
        if Pathname(File.dirname(__FILE__)).join("../../../#{fetch(:translations_path)}").exist?
          execute :drush, 'locale:import:all', "--root=#{release_path.join(fetch(:drupal_root))}",
                  translations_dir, '--override=all', '--type=customized', '--yes', "--uri=http://#{site}"
        end

        maintenance! enable: false
      end
    end
  end

  namespace :cache do
    task :clear do
      on roles(:app) do
        within release_path.join(fetch(:drupal_root)) do
          # execute :drupal, 'cache:rebuild'
          cache_clear
        end
      end
    end
  end

  namespace :symlink do
    task :htdocs do
      on roles(:app) do
        execute :rm, '-f', deploy_path.join('htdocs')
        execute :ln, '-sf', release_path, deploy_path.join('htdocs')
      end
    end

    task :htaccess do
      on roles(:app) do
        execute :rm, '-f', release_path.join('web/.htaccess')
        execute :ln, '-sf', release_path.join('htaccess.txt'), release_path.join('web/.htaccess')
      end
    end
  end

  namespace :cleanup do
    task :unharden do
      on roles(:app) do
        real_current = capture(:readlink, current_path)
        dirs = capture(:ls, '-xd', releases_path.join('*/web/sites/*')).split.find_all do |dir|
          !dir.match(real_current)
        end
        dirs.each do |default_dir|
          execute :chmod, 'u+w', default_dir
        end
      end
    end

    task :harden do
      on roles(:app) do
        real_current = capture(:readlink, current_path)
        dirs = capture(:ls, '-xd', releases_path.join('*/web/sites/*')).split.find_all do |dir|
          !dir.match(real_current)
        end
        dirs.each do |default_dir|
          execute :chmod, 'u-w', default_dir
        end
      end
    end
  end
end
# rubocop:enable Metrics/BlockLength

after 'deploy:updating', 'drupal:set_paths'
before 'deploy:updated', 'drupal:site:offline'
after 'deploy:updated', 'composer:install'
# before 'deploy:updated', 'drupal:site:backup'
after 'deploy:updated', 'drupal:update'
after 'deploy:published', 'drupal:site:online'
after 'deploy:published', 'drupal:cache:clear'
before 'deploy:cleanup', 'drupal:cleanup:unharden'
after 'deploy:cleanup', 'drupal:cleanup:harden'
