#
# apt_preferences.rb - ruby interface for APT preferences
# Copyright (C) 2004       Masato Taruishi <taru@debian.org>
# Copyright (C) 2009-2014  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
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

module Debian

  class AptPreferences

    class Pin < Hash
      def initialize( buf )
        @buf = buf
        buf.each_line do |line|
          if /(\S+): (.+)$/ =~ line
            self[$1] = "" if self[$1] == nil
            self[$1] << $2
          end
        end
      end

      def listbugs?
        if (/Pinned by apt-listbugs/ =~ self["Explanation"])
          return true
        end
        return false
      end

      def to_s
        @buf.to_s
      end

    end

    def initialize( file = "/etc/apt/preferences.d/apt-listbugs" )
      @pins = []
      open(file) { |io|
        @pref = io.read
      }
      _each_pin do |pin|
        @pins << Pin.new(pin)
      end
    end

    def _each_pin
      buf = ""
      @pref.each_line do |line|
        case line
        when "\n"
          if buf != ""
            yield buf
            buf = ""
          end
        else
          buf << line
        end
      end
      yield buf if buf != ""
    end

    attr_reader :pins

    def filter( pkg_keys = [], out = $stdout, remainder = nil )
      _each_pin do |pin|
        p = Pin.new(pin)
        if ! p.listbugs? || pkg_keys.include?( p["Package"] )
          out.puts pin
          out.puts ""
        else
          if remainder != nil
            remainder.puts pin
            remainder.puts ""
          end
        end
      end
    end

  end

end

