#!/usr/bin/env ruby
# -*- ruby -*-
#
# Copyright (c) 2000-2001 Akinori MUSHA
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

RCS_ID = %q$Idaemons: /home/cvs/pkgtools/portsdb,v 1.18 2001/10/02 21:47:51 knu Exp $
RCS_REVISION = RCS_ID.split[2]
MYNAME = File.basename($0)

require "optparse"
require "pkgtools"

COLUMNSIZE = 24
NEXTLINE = "\n%*s" % [5 + COLUMNSIZE, '']

$regex = false
$force = false
$update_index = false
$update_db = false
#$slave_recursive = false
$master_recursive = false
$recursive = false
$upward_recursive = false
$exclude_ports = []

def main(argv)
  usage = <<-"EOF"
usage: #{MYNAME} [-hfMrRuU] [-x port_glob] [port_glob ...]
    EOF

  banner = <<-"EOF"
#{MYNAME} rev.#{RCS_REVISION}

#{usage}
  EOF

  OptionParser.new(banner, COLUMNSIZE) do |opts|
    opts.def_option("-h", "--help", "Show this message") {
      print opts
      return 0
    }

    opts.def_option("-f", "--force", "Force to update database regardless of timestamps") {
      |$force|
    }

    opts.def_option("-M", "--master-recursive", "List all the master ports of the given packages#{NEXTLINE}as well") {
      |$master_recursive|
    }

    opts.def_option("-r", "--recursive", "List all those depending on the given packages#{NEXTLINE}as well") {
      |$recursive|
    }

    opts.def_option("-R", "--upward-recursive", "List all those required by the given packages#{NEXTLINE}as well") {
      |$upward_recursive|
    }

#    opts.def_option("-S", "--slave-recursive", "List all the slave ports of the given packages#{NEXTLINE}as well") {
#      |$slave_recursive|
#    }

    opts.def_option("-u", "--update", "Update INDEX.db and INDEX.rbo") {
      |$update_db|
    }

    opts.def_option("-U", "--updateindex", "Update INDEX") {
      |$update_index|
    }

    opts.def_option("-x", "--exclude=GLOB", "Exclude ports matching the specified glob#{NEXTLINE}pattern") {
      |arg|
      begin
	pattern = parse_pattern(arg, $regex)
      rescue RegexpError => e
	warning_message e.message.capitalize
	break
      end

      $exclude_ports |= $portsdb.glob(pattern).collect { |portinfo| portinfo.origin }
    }

    opts.def_option("-E", "--regex", "Treat glob patterns as extended regexp#{NEXTLINE}(deprecated; use :RE instead)") {
      |$regex|
    }

    opts.def_tail_option '
If a port_glob is specified, the ports matching the pattern are listed.
A pattern can be either in the pkgname from or in the origin form including
a slash (\'/\'), and in which you can use wildcards *, ?, and [..],
or an extended regular expression preceded by a colon (:).

Environment Variables [default]:
    PORTSDIR                 ports directory [/usr/ports]
    PORTS_INDEX              ports index file [$PORTSDIR/INDEX]
    PORTS_DBDIR              ports db directory [$PORTSDIR]'

    if argv.empty?
      print opts
      return 0
    end

    begin
      opts.order!(argv)

      if $update_index
	$portsdb.update
      end

      if $update_db
	$portsdb.update_db($force)
      end

      list = []
      
      opts.order(*argv) do |arg|
	pattern = $portsdb.strip(arg) || arg	# allow pkgname_glob

	begin
	  pattern = parse_pattern(pattern, $regex)
	rescue RegexpError => e
	  warning_message e.message.capitalize
	  next
	end

	$portsdb.glob(pattern) do |portinfo|
	  list |= $portsdb.recurse(portinfo, $recursive, $upward_recursive)
	end
      end

      ports = []

      list.each do |portinfo|
	if $master_recursive
	  if masters = portinfo.masters
	    masters.each do |master|
	      ports << $portsdb.origin(master)
	    end
	  end
	end

        ports << portinfo.origin
      end

      ports -= $exclude_ports

      puts $portsdb.sort(ports)
    rescue OptionParser::ParseError => e
      STDERR.puts "#{MYNAME}: #{e}", usage
      exit 64
    end
  end

  0
end

if $0 == __FILE__
  exit main(ARGV)
end
