summaryrefslogtreecommitdiff
path: root/lib/license/management/shell.rb
blob: 672046026ddafe8e7ced0705d09e50f9c0ba2d64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# frozen_string_literal: true

module License
  module Management
    class Shell
      attr_reader :custom_certificate_path, :logger

      def initialize(logger: License::Management.logger, certificate: ENV['ADDITIONAL_CA_CERT_BUNDLE'])
        @logger = logger
        @custom_certificate_path = Pathname.new('/usr/local/share/ca-certificates/custom.crt')
        trust!(certificate)
      end

      def execute(command, env: {})
        expanded_command = expand(command)
        logger.debug(expanded_command)

        stdout, stderr, status = Open3.capture3(env, expanded_command)

        logger.debug(stdout) unless stdout.nil? || stdout.empty?
        logger.error(stderr) unless status.success?
        [stdout, stderr, status]
      end

      def sh(command, env: {})
        execute("sh -c '#{expand(command)}'", env: env)
      end

      def custom_certificate_installed?
        present?(ENV['ADDITIONAL_CA_CERT_BUNDLE']) && custom_certificate_path.exist?
      end

      private

      def expand(command)
        Array(command).flatten.map(&:to_s).join(' ')
      end

      def trust!(certificate)
        return unless present?(certificate)

        custom_certificate_path.write(certificate)
        execute("openssl x509 -in #{custom_certificate_path} -text -noout")
        execute('update-ca-certificates -v')
      end

      def present?(item)
        !item.nil? && !item.empty?
      end
    end
  end
end