# frozen_string_literal: true
#
# Copyright (C) 2016 Harald Sitter <sitter@kde.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) version 3, or any
# later version accepted by the membership of KDE e.V. (or its
# successor approved by the membership of KDE e.V.), which shall
# act as a proxy defined in Section 6 of version 3 of the license.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.  If not, see <http://www.gnu.org/licenses/>.

require 'gir_ffi'
require 'yaml'

KDEDE = 'org.kde.development'.freeze
DEBIAN = __dir__

# Contents grapple api wrapper
class Grapple
  BASE_URL = 'https://contents.neon.kde.org/v1'.freeze

  def initialize
    require 'faraday'
    require 'logger'
    require 'json'
    @connection = Faraday.new(url: BASE_URL) do |c|
      c.request :url_encoded
      c.response :logger, ::Logger.new(STDOUT), bodies: true
      c.adapter Faraday.default_adapter
    end
  end

  def pools
    JSON.parse(@connection.get('pools').body)
  end

  # An archive
  class Archive
    def initialize(id)
      @connection = Faraday.new(url: "#{BASE_URL}/find/#{id}") do |c|
        c.request :url_encoded
        c.response :logger, ::Logger.new(STDOUT), bodies: true
        c.adapter Faraday.default_adapter
      end
    end

    def find(query)
      JSON.parse(@connection.get('') { |req| req.params['q'] = query }.body)
    end

    def find_all_packages(query)
      find(query).values.flatten.uniq.compact
    end
  end
end

statics_components = YAML.load_file("#{DEBIAN}/static_components.yaml")

GirFFI.setup(:AppStream, '1.0')
pool = AppStream::Pool.new.tap(&:load)

depends = []
recommends = []

statics_components[:depends].each do |id|
  pool.components_by_id(id).each do |component|
    depends += component.pkgnames.to_a
  end
end

pool.components.each do |component|
  component.extends.each do |extendee|
    recommends += component.pkgnames.to_a if extendee == KDEDE
  end
end

all_frameworks = []
neon_pool = Grapple.new.pools.fetch('neon-bionic-user')
neon_pool.each do |id|
  if id == "archive.neon.kde.org/user/dists/bionic"
    archive = Grapple::Archive.new(id)
    all_frameworks += archive.find_all_packages('*/cmake/*/KF5*Config.cmake')
  end
end
all_frameworks.uniq!

File.open("#{DEBIAN}/substvars", 'a') do |file|
  file.puts("appstream:Depends=#{depends.join(', ')}")
  file.puts("appstream:Recommends=#{recommends.join(', ')}")
  file.puts("frameworks:All=#{all_frameworks.join(', ')}")
end
