require_relative "packages-groonga-org-package-task"

class GroongaPackageTask < PackagesGroongaOrgPackageTask
  def initialize
    super("groonga", detect_version, detect_release_time)
    @archive_name = "groonga-#{@version}.tar.gz"
    @original_archive_name = @archive_name
  end

  private
  def detect_version
    version_env = ENV["VERSION"]
    return version_env if version_env

    base_version_file = File.join(__dir__,
                                  "..",
                                  "base_version")
    version = File.read(base_version_file).chomp
  end

  def detect_target_apache_arrow_version
    cmakelists = File.join(__dir__,
                           "..",
                           "vendor",
                           "apache-arrow-source",
                           "cpp",
                           "CMakeLists.txt")
    matched = File.read(cmakelists).match(/^set\(ARROW_VERSION "(.+?)"\)/)
    version = matched[1]
    matched = version.match(/-SNAPSHOT\z/)
    if matched
      major_version = matched.pre_match.split(".", 2)[0].to_i
      previous_major_version = major_version - 1
      "#{previous_major_version}.0.0"
    else
      version
    end
  end

  def define_archive_task
    file @original_archive_name do
      File.symlink("../#{@original_archive_name}",
                   @original_archive_name)
    end
  end

  def docker_build_options(os, architecture)
    [
      "--build-arg",
      "APACHE_ARROW_VERSION=#{detect_target_apache_arrow_version}",
    ]
  end

  def apt_targets_default
    [
      "debian-buster",
      "debian-buster-i386",
    ]
  end

  def yum_targets_default
    [
      "centos-7",
      "centos-8",
    ]
  end

  def yum_expand_variable(key)
    case key
    when "APACHE_ARROW_VERSION"
      detect_target_apache_arrow_version
    else
      super
    end
  end

  def windows_targets_default
    [
      "#{@package}-#{@version}-x64-vs2019.zip",
      "#{@package}-#{@version}-x64-vs2019-with-vcruntime.zip",
      "#{@package}-#{@version}-x86-vs2019.zip",
      "#{@package}-#{@version}-x86-vs2019-with-vcruntime.zip",
      "#{@package}-#{@version}-x64-vs2017.zip",
      "#{@package}-#{@version}-x64-vs2017-with-vcruntime.zip",
      "#{@package}-#{@version}-x86-vs2017.zip",
      "#{@package}-#{@version}-x86-vs2017-with-vcruntime.zip",
    ]
  end

  def use_built_package?
    true
  end

  def built_package_url(target_namespace, target)
    url = "https://github.com/groonga/groonga/releases/download/v#{@version}/"
    if target_namespace == :apt and !target.end_with?("-i386")
      url << "#{target}-amd64.tar.gz"
    elsif target_namespace == :windows
      url << "#{target}"
    else
      url << "#{target}.tar.gz"
    end
    url
  end

  def built_package_n_split_components
    3
  end
end

task = GroongaPackageTask.new
task.define
