# frozen_string_literal: true

module Gitlab
  module QA
    module Component
      class PipelineOps < Base
        def start(gitlab, project_name)
          create_and_execute_pipeline_script(gitlab, project_name)
        end

        def check_status(gitlab)
          pipeline_status = gitlab.docker.exec(
            gitlab.name, wait_for_pipeline)

          case pipeline_status
          when 'success'
            puts "Pipeline succeeded!"
            nil
          when 'failed'
            raise StandardError, "Pipeline failed."
          else
            puts "Pipeline is currently #{pipeline_status}"
          end
        end

        private

        def create_and_execute_pipeline_script(gitlab, project_name)
          setup_src_path = File.expand_path('../../../../support/pipeline', __dir__)
          setup_dest_path = '/tmp/setup-scripts'

          gitlab.docker.copy(gitlab.name, setup_src_path, setup_dest_path)

          gitlab.docker.exec(
            gitlab.name,
            "PROJECT_NAME='#{project_name}' gitlab-rails runner #{setup_dest_path}/create_for_projectname.rb"
          )
        end

        def wait_for_pipeline
          <<~SHELL
            gitlab-rails runner "
              latest_pipeline = Ci::Pipeline.last
              # wait for the pipeline to complete
              loop do
                latest_pipeline.reload
                break if latest_pipeline.complete?
                sleep 1
              end
              puts latest_pipeline.status
            "
          SHELL
        end
      end
    end
  end
end
