#!/usr/bin/env ruby
#
# Copyright (C) 2019 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/>.

# Updates the data/ dir with new extraction

require 'fileutils'
require 'shellwords'
require 'tty/command'
require 'tmpdir'

cmd = TTY::Command.new
out, _err = cmd.run('apt-cache', 'search', '--names-only',
                    'language-pack-gnome-',
                    only_output_on_error: true)

packages = out.strip.split($/)
# throw the short description away
packages = packages.collect { |x| x.split(' ', 2)[0] }

src_dir = "#{File.dirname(__dir__)}/data"
FileUtils.rm_rf(src_dir)

packages.each do |package|
  Dir.mktmpdir do |tmpdir|
    Dir.chdir(tmpdir) do
      cmd.run('apt-get', 'download', package)
      cmd.run('dpkg-deb', '-x', Dir.glob('*.deb')[0], '.')
      Dir.glob('**/libpwquality.mo').each do |file|
        path = File.dirname(file)
        target_dir = "#{src_dir}/#{path}"
        FileUtils.mkpath(target_dir, verbose: true)
        FileUtils.cp(file, target_dir, verbose: true)
      end
    end
  end
end

# dirty os-release parser to then dump it into a file. this allows the maint
# script generator to prevent installation on a series other than the one
# the data was generated from
VERSION_CODENAME = begin
  data = File.read('/etc/os-release')
  data.split($/).each do |line|
    next unless line.start_with?('VERSION_CODENAME=')

    _key, value = line.split('=')
    value = Shellwords.split(value)
    value = value[0] if value.size == 1
    break value
  end
end
File.write("#{__dir__}/version_codename", VERSION_CODENAME)
