# Copyright (C) 2018 Harald Sitter <sitter@kde.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 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 14 of version 3 of the license.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

require_relative 'test_helper'
require_relative '../usr/lib/neon_update/calamares_groups'

class NeonMigrateUnstableGroups < Minitest::Test
  def setup
    @datadir = File.realpath("#{__dir__}/data/neon-migrate-unstable-groups/")
    @tmpdir = Dir.mktmpdir
    Dir.chdir(@tmpdir)
    FileUtils.cp_r("#{@datadir}/.", '.')
    ENV['ROOT'] = @tmpdir
  end

  def teardown
    FileUtils.rm_r(@tmpdir)
    ENV.delete('ROOT')
  end

  def test_run
    passwd = mock('passwd')
    passwd.expects(:name).returns('xme')
    Etc.expects(:getpwuid).returns(passwd)
    groups = Migrator::ADD_GROUPS.collect { |n| [Etc::Group.new(n, nil, nil, 'xme')] }
    groups += Migrator::REMOVE_GROUPS.collect { |n| [Etc::Group.new(n, nil, nil, 'xme')] }
    Etc.expects(:group).multiple_yields(*groups)
    Migrator::ADD_GROUPS.each do |g|
      Object.any_instance.expects(:system).with('adduser', 'xme', g).returns(true)
    end
    Migrator::REMOVE_GROUPS.each do |g|
      Object.any_instance.expects(:system).with('deluser', 'xme', g).returns(true)
    end

    Migrator.new.run

    assert File.exist?("#{@tmpdir}/var/lib/neon/update-calamares-groups")
  end
end
