#!/usr/bin/env 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/pkg_glob,v 1.1 2001/07/26 18:35:58 knu Exp $
RCS_REVISION = RCS_ID.split[2]
MYNAME = File.basename($0)

require "optparse"
require "pkgtools"

$all = false
$pkg_delete_args = []
$interactive = false
$noexecute = false
$recursive = false
$upward_recursive = false
$exclude_packages = []

case MYNAME
when 'pkg_deinstall'
  $service = :deinstall
else
  $service = :list
end
$service_verb = $service.to_s

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

def main(argv)
  case $service
  when :deinstall
    usage = <<-"EOF"
usage: #{MYNAME} [-hainrR] [-e args] [-x pkgname_glob] [...]
  EOF
  else
    usage = <<-"EOF"
usage: #{MYNAME} [-harR] [-x pkgname_glob] [...]
  EOF
  end

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

#{usage}
  EOF

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

    opts.on("-a", "--all", "#{$service_verb.capitalize} all the installed packages") {
      |$all|
    }

    if $service == :deinstall
      opts.on("-e", "--cmd_args=ARGS", "Specify arguments to pass to pkg_delete(1)") {
	|args|
	$pkg_delete_args.push *shellwords(args)
      }

      opts.on("-i", "--interactive", "Turn on interactive mode") {
	|$interactive|
      }

      opts.on("-n", "--noexecute", "Do not deinstall any packages, but just show what#{NEXTLINE}would be done") {
	|$noexecute|
	if $noexecute
	  $interactive = false
	end
      }
    end

    opts.on("-r", "--recursive", "#{$service_verb.capitalize} all those depending on the given#{NEXTLINE}packages as well") {
      |$recursive|
      $sort = true
    }

    opts.on("-R", "--upward-recursive", "#{$service_verb.capitalize} all those required by the given#{NEXTLINE}packages as well") {
      |$upward_recursive|
      $sort = true
    }

    opts.on("-x", "--exclude=GLOB", "Exclude packages matching the specified glob#{NEXTLINE}pattern") {
      |arg|
      $exclude_packages |= $pkgdb.glob(arg, false)
    }

    opts.on_tail <<-"EOF".chomp

pkgname_glob is one of these: a full pkgname, a pkgname w/o version,
or a shell glob pattern in which you can use the wildcards *, ?, and [..].
The package list is automatically sorted in dependency order.

Environment Variables [default]:
    PKG_DBDIR                packages DB directory [/var/db/pkg]
    EOF

    tasks = []

    begin
      opts.parse!(argv)

      if argv.empty? && !$all
	print opts
	return 0
      end

      all = '*'
      argv << all

      opts.order(*argv) do |arg|
	if arg.equal? all
	  next unless $all
	end

	$pkgdb.glob(arg, false).each do |pkgname|
	  if $upward_recursive
	    deps = $pkgdb.pkgdep(pkgname)

	    if deps && !deps.empty?
	      deps.each do |i|
		tasks << i unless $exclude_packages.include? i
	      end
	    end
	  end

	  tasks << pkgname unless $exclude_packages.include? pkgname

	  if $recursive
	    req_by = $pkgdb.required_by(pkgname)

	    if req_by
	      req_by.reject do |i|
		tasks << i unless $exclude_packages.include? i
	      end
	    end
	  end
	end
      end
 
      $pkgdb.sort!(tasks)
    rescue OptionParser::ParseError => e
      STDERR.puts "#{MYNAME}: #{e}", usage
      exit 64
    end

    case $service
    when :deinstall
      tasks.reverse_each do |pkgname|
	progress_message "Deinstalling '#{pkgname}'"

	next if $noexecute
	next if $interactive && !prompt_yesno('OK?', true)

	cmdargs = ['pkg_delete', *$pkg_delete_args] << pkgname

	system *cmdargs
      end
    else
      puts tasks
    end

    return 0
  end
end

if $0 == __FILE__
  for sig in [2, 3, 15]
    trap(sig) do
      signal_handler(sig)
    end
  end

  exit main(ARGV)
end
