#!/usr/bin/env ruby

# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

# frozen_string_literal: true

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = 'Usage: bin/dev [options] [command]'

  opts.on(
    '-iIMAGE', '--image=IMAGE',
    'Specify Docker image (eg. ruby:latest)'
  ) { |val| options[:image] = val }

  opts.on(
    '-fFRAMEWORKS', '--frameworks=FRAMEWORKS',
    'Specify frameworks to test (eg. rails:master,sinatra)'
  ) { |val| options[:frameworks] = val }

  opts.on(
    '-s', '--skip-build',
    'Skip building image'
  ) { |val| options[:skip_build] = val }
end.parse!

USER_ID_GROUP = %w[u g].map { |f| `id -#{f}`.chomp }.join(':')

RUBY_IMAGE = options.fetch(:image, 'ruby:latest')
FRAMEWORKS = options.fetch(:frameworks, 'rails')

IMAGE_PATH_SAFE = RUBY_IMAGE.tr(':', '_')
IMAGE_NAME = "apm-agent-ruby:#{IMAGE_PATH_SAFE}"
VENDOR_PATH = "/vendor/#{IMAGE_PATH_SAFE}"

def run(cmd)
  "IMAGE_NAME=#{IMAGE_NAME} USER_ID_GROUP=#{USER_ID_GROUP} #{cmd}".tap do |str|
    puts str
    system str
  end
end

unless options[:skip_build]
  run 'docker-compose build ' \
    " --build-arg RUBY_IMAGE=#{RUBY_IMAGE}" \
    " --build-arg USER_ID_GROUP=#{USER_ID_GROUP}" \
    " --build-arg FRAMEWORKS=#{FRAMEWORKS}" \
    " --build-arg VENDOR_PATH=#{VENDOR_PATH}"
  exit $?.exitstatus unless $?.success?
end

run 'docker-compose run' \
  ' --rm' \
  " specs #{ARGV.join}"

exit $?.exitstatus unless $?.success?
