# frozen_string_literal: true

# Macroweb hardening a deploy során:
# Case: https://atrium.macroweb.hu/macroweb/node/41212
#   drupal:harden:htaccess   - a shared/web/.htaccess-be beszúrja / frissíti a MACROWEB-HARDENING blokkot
#                              (install.php, README/INSTALL/LICENSE/CHANGELOG, package.json, error_log stb. tiltása)
#   drupal:harden:settings   - figyelmeztet, ha a shared settings.php-ban update_free_access nem FALSE
#   drupal:harden:http_check - a deploy végén HTTP-n ellenőrzi az éles viselkedést (csak ha :site_url vagy SITE_URL be van állítva)
#
# Kipróbálás írás nélkül (csak kiírja, mit csinálna):
#   HARDEN_DRY_RUN=1 bundle exec cap demo drupal:harden:htaccess
#
# A blokk tartalma: lib/capistrano/macroweb_hardening.rb

require 'stringio'
require 'net/http'
require 'uri'
require_relative '../macroweb_hardening'

# rubocop:disable Metrics/BlockLength
namespace :drupal do
  namespace :harden do
    desc 'MACROWEB-HARDENING blokk beszúrása / frissítése a shared web/.htaccess-ben'
    task :htaccess do
      unless Array(fetch(:linked_files, [])).include?('web/.htaccess')
        run_locally do
          info 'drupal:harden:htaccess kimarad: a web/.htaccess nem linked file, a gitben kell karbantartani ' \
               '(ruby -r ./lib/capistrano/macroweb_hardening.rb -e \'MacrowebHardening.apply_file("web/.htaccess")\')'
        end
        next
      end

      on roles(:app) do
        file = shared_path.join('web/.htaccess')
        unless test("[ -f #{file} ]")
          warn "#{file} nem létezik, a hardening blokk kimarad"
          next
        end

        io = StringIO.new
        download! file.to_s, io
        current = io.string.dup.force_encoding('UTF-8')
        updated, action = MacrowebHardening.apply(current)

        if action == :unchanged
          info "#{file}: a MACROWEB-HARDENING blokk naprakész"
          next
        end

        if ENV['HARDEN_DRY_RUN']
          info "[DRY RUN] #{file}: a művelet ez lenne: #{action}"
          info "[DRY RUN] Az új tartalom eleje:\n#{updated.lines.first(40).join}"
          next
        end

        backup = "#{file}.bak-#{Time.now.strftime('%Y%m%d%H%M%S')}"
        tmp = "#{file}.macroweb-tmp"
        execute :cp, '-p', file, backup
        upload! StringIO.new(updated), tmp
        # cat > : a fájl inode-ja, tulajdonosa és jogai megmaradnak (ha symlink, a célját írja)
        execute "cat #{tmp} > #{file} && rm -f #{tmp}"
        info "#{file}: MACROWEB-HARDENING blokk #{action} (mentés: #{backup})"
      end
    end

    desc 'Figyelmeztet, ha a shared settings.php-ban update_free_access nem FALSE'
    task :settings do
      on roles(:app) do
        dir = shared_path.join('web/sites/default')
        %w[settings.php settings.local.php].each do |name|
          file = dir.join(name)
          next unless test("[ -f #{file} ]")

          io = StringIO.new
          download! file.to_s, io
          value = MacrowebHardening.update_free_access(io.string)
          if value.nil?
            info "#{name}: update_free_access nincs beállítva (a Drupal alapból tiltja)" if name == 'settings.php'
          elsif value.casecmp('FALSE').zero?
            info "#{name}: update_free_access = FALSE"
          else
            warn '!' * 70
            warn "#{file}: $settings['update_free_access'] = #{value}"
            warn 'Az /update.php így bejelentkezés nélkül is elérhető. Állítsd FALSE-ra!'
            warn '!' * 70
          end
        end
      end
    end

    desc 'HTTP-ellenőrzés a deploy után (stage-fájlban: set :site_url, "https://...")'
    task :http_check do
      # Kézi futtatásnál felülírható: SITE_URL=https://... bundle exec cap demo drupal:harden:http_check
      site_url = ENV['SITE_URL'] || fetch(:site_url, nil)
      if site_url.nil? || site_url.to_s.strip.empty?
        run_locally { info 'drupal:harden:http_check kimarad: nincs :site_url beállítva a stage-fájlban' }
        next
      end

      base = site_url.to_s.sub(%r{/+\z}, '')
      code_of = lambda do |path|
        uri = URI("#{base}/#{path}")
        Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 15, read_timeout: 15) do |http|
          http.request(Net::HTTP::Get.new(uri)).code.to_i
        end
      rescue StandardError => e
        "HIBA (#{e.class})"
      end

      problems = []
      home = code_of.call('')
      run_locally do
        if home == 401
          warn "drupal:harden:http_check: #{base} HTTP auth mögött van (401), nem ellenőrizhető"
          next
        end

        MacrowebHardening::OPEN_PATHS.each do |p|
          c = code_of.call(p)
          problems << "/#{p}: #{c} (200 kellene)" unless c == 200
        end
        MacrowebHardening::BLOCKED_PATHS.each do |p|
          c = code_of.call(p)
          problems << "/#{p}: #{c} (kiszolgálva, 403/404 kellene)" if c == 200
        end
        c = code_of.call(MacrowebHardening::UPDATE_PATH)
        problems << "/#{MacrowebHardening::UPDATE_PATH}: #{c} (403 kellene; update_free_access?)" if c == 200

        if problems.empty?
          info "drupal:harden:http_check: #{base} rendben"
        else
          warn "drupal:harden:http_check: #{base} problémák:"
          problems.each { |pr| warn "  #{pr}" }
        end
      end
    end
  end
end
# rubocop:enable Metrics/BlockLength

# A deploy:check:linked_files után: ekkor a shared/web/.htaccess már biztosan létezik
# (különben a check elhasal), és még a release symlinkjei előtt vagyunk.
after 'deploy:check:linked_files', 'drupal:harden:htaccess'
after 'deploy:check:linked_files', 'drupal:harden:settings'
after 'deploy:finished', 'drupal:harden:http_check'
