#!/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.3 2001/08/08 20:43:19 knu Exp $
RCS_REVISION = RCS_ID.split[2]
MYNAME = File.basename($0)

require "optparse"
require "pkgtools"

$all = false
$pkg_delete_args = []
$preserve_shlib = false
$interactive = false
$noexecute = false
$verbose = 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 = 12
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", "#{$service_verb.capitalize} all the installed packages") {
      |$all|
    }

    if $service == :deinstall
      opts.on("-d", "Remove empty directories created by file cleanup [*]") {
	$pkg_delete_args.push '-d'
      }

      opts.on("-D", "Do not execute deinstallation scripts [*]") {
	$pkg_delete_args.push '-D'
      }

      opts.on("-f", "Force removal of the packages [*]") {
	$pkg_delete_args.push '-f'
      }

      opts.on("-i", "Request confirmation for each package removal [*]") {
	|$interactive|
	if $interactive
	  $verbose = true
	end

	$pkg_delete_args.push '-i'
      }

      opts.on("-n", "Do not actually deinstall a package, just report the steps#{NEXTLINE}that would be taken if it were [*]") {
	|$noexecute|
	if $noexecute
	  $verbose = true
	  $interactive = false
	end

	$pkg_delete_args.push '-n'
      }

      opts.on("-pPREFIX", "Set prefix [*]") {
	|prefix|
	$pkg_delete_args.push '-p', prefix
      }

      opts.on("-v", "Turn on verbose output [*]") {
	|$verbose|
	$pkg_delete_args.push '-v'
      }

      opts.on("-P", "Preserve shared libraries (Do not delete *.so/*.so.n)") {
	|$preserve_shlib|
      }

      opts.on_tail <<-"EOF".chomp

[*] These options are transparently passed to pkg_delete(1).
      EOF
    end

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

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

    opts.on("-xGLOB", "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
      failed_pkgnames = []

      tasks.reverse_each do |pkgname|
	progress_message "Deinstalling '#{pkgname}'"

	contents_file = $pkgdb.pkg_contents(pkgname)

	if $noexecute
	  if $preserve_shlib
	    progress_message '(Shared libraries will be preserved in the real execution)'
	  end
	else
	  if $preserve_shlib
	    unless File.writable?(contents_file)
	      warning_message "Cannot modify '#{contents_file}' to preserve shared libraries."
	      failed_pkgnames << pkgname
	      next
	    end

	    contents_file_bak = File.join($pkgdb.pkgdir(pkgname),
					  pkgname + ".+CONTENTS.bak")

	    changed_lines = subst_file(/^[^@].*\.so(\.\d+)*$/,
				       '@comment shlib preserved',
				       contents_file,
				       contents_file_bak)

	    if $verbose && changed_lines
	      changed_lines.each do |shlib,|
		progress_message 'Preserving ' + shlib
	      end
	    end
	  end
	end

	cmdargs = [PkgDB::CMD[:pkg_delete], *$pkg_delete_args] << pkgname

	system(*cmdargs)

	unless $noexecute
	  if File.exists?(contents_file)
	    failed_pkgnames << pkgname

	    if $preserve_shlib
	      system '/bin/mv', '-f', contents_file_bak, contents_file
	    end
	  else
	    if $preserve_shlib
	      system '/bin/rm', '-f', contents_file_bak
	    end
	  end
	end
      end

      unless failed_pkgnames.empty?
	warning_message "Some packages could not be deinstalled due to errors:"
	failed_pkgnames.each do |pkgname|
	  STDERR.puts "\t" + pkgname
	end
      end

      return failed_pkgnames.size
    end

    puts tasks

    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
