#!/usr/bin/ruby
#
# migratepins: migrates all apt-listbugs-managed pins from
#              /etc/apt/preferences to <tmpdir>/apt-listbugs
#              and everything else to <tmpdir>/preferences
#
# Copyright (C) 2009       Ryan Niebur <ryan@debian.org>
# Copyright (C) 2014-2015  Francesco Poli <invernomuto@paranoici.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) any later version.
#
#  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 with
#  the Debian GNU/Linux distribution in file /usr/share/common-licenses/GPL-2;
#  if not, write to the Free Software Foundation, Inc., 51 Franklin St,
#  Fifth Floor, Boston, MA 02110-1301, USA.
#
#

if ! File.expand_path(__FILE__).match(/^\/usr\/lib\/ruby\/vendor_ruby\/aptlistbugs\//)
  $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), ".."))
end

require 'gettext'
include GetText

GetText::bindtextdomain("apt-listbugs")

require 'aptlistbugs/debian/apt_preferences'
require 'tmpdir'

# create a temporary directory to split APT preferences
# and print its name to stdout
dest_dir = Dir.mktmpdir('pin_migration_')
puts dest_dir

# read APT preferences from /etc/apt/preferences
pref_file = "/etc/apt/preferences"
begin
  p = Debian::AptPreferences.new(pref_file)
rescue Errno::ENOENT
  $stderr.puts sprintf("Cannot find %s: exiting!", pref_file) if $DEBUG
  exit 0
rescue Errno::EACCES
  $stderr.puts _("E: ") + sprintf(_("Cannot read from %s"), pref_file)
  exit 1
rescue
  $stderr.puts _("E: ") + "#{$!}"
  exit 1
end

# split APT preferences:
# all apt-listbugs-managed pins go to dest_dir/apt-listbugs
# everything else goes to dest_dir/preferences
new_pref_file = File.open(dest_dir + "/preferences", "w")
new_aptl_file = File.open(dest_dir + "/apt-listbugs", "w")
p.filter( [], new_pref_file, new_aptl_file )

