#!/usr/bin/env ruby
# frozen_string_literal: true

# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2019-2020 Harald Sitter <sitter@kde.org>

require 'fileutils'

marker = '/var/lib/neon/flathub-set-up'
bin = '/usr/bin/flatpak'

exit 0 unless File.executable?(bin) || File.exist?(marker)

# in seconds
def wait_time
  @wait_times ||= [1, 5]
  @wait_times.pop || 30
end

# After 10 iterations we'll assume network isn't going to come online and give
# up. We'll try again next boot.
10.times do
  # wait for actual network; we ignore the return value. either this succeeded
  # and we have network or we'll try again after a bit.
  system('nm-online', '--timeout=60')

  if system(bin, 'remote-add', '--system', '--if-not-exists',
            'flathub', 'https://flathub.org/repo/flathub.flatpakrepo')
    FileUtils.mkpath(File.dirname(marker))
    FileUtils.touch(marker)
    break
  end

  puts 'Failed to add flathub. Trying again in a bit.'
  sleep wait_time
end
