#!/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/pkg_glob,v 1.19 2001/09/21 21:43:14 knu Exp $
RCS_REVISION = RCS_ID.split[2]
MYNAME = File.basename($0)

require "optparse"
require "pkgtools"

$all = false
$pkg_delete_args = []
$preserve_shlib = false
$regex = 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 = 22
NEXTLINE = "\n%*s" % [5 + COLUMNSIZE, '']

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

  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("-a", "--all", "#{$service_verb.capitalize} all the installed packages") {
      |$all|
      $recursive = false
      $upward_recursive = false
    }

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

    opts.def_option("-D", "--noscripts", "Do not execute deinstallation scripts [*]") {
      $pkg_delete_args.push '-D'
    } if $service == :deinstall

    opts.def_option("-f", "--force", "Force removal of the packages [*]") {
      $pkg_delete_args.push '-f'
    } if $service == :deinstall

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

      $pkg_delete_args.push '-i'
    } if $service == :deinstall

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

      $pkg_delete_args.push '-n'
    } if $service == :deinstall

    opts.def_option("-p", "--prefix=PREFIX", "Set prefix [*]") {
      |prefix|
      $pkg_delete_args.push '-p', prefix
    } if $service == :deinstall

    opts.def_option("-P", "--preserve", "Preserve shared libraries (Don't delete *.so/*.so.n)") {
      |$preserve_shlib|
    } if $service == :deinstall

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

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

    opts.def_option("-v", "--verbose", "Turn on verbose output [*]") {
      |$verbose|
      $pkg_delete_args.push '-v'
    } if $service == :deinstall

    opts.def_tail_option <<-"EOF".chomp if $service == :deinstall

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

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

      $exclude_packages |= $pkgdb.glob(pattern, false)
    }

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

    opts.def_tail_option '
pkgname_glob is one of these: a full pkgname, a pkgname w/o version,
a shell glob pattern in which you can use wildcards *, ?, and [..],
an extended regular expression preceded by a colon (:), or a date
spec preceded by either < or >.  See pkg_glob(1) for details.
The package list is automatically sorted in dependency order.

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

    tasks = []

    begin
      opts.order!(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

	  pattern = arg
	else
	  pattern = $pkgdb.strip(arg)

	  next if pattern.nil?

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

	$pkgdb.glob(pattern, false).each do |pkgname|
	  tasks |= $pkgdb.recurse(pkgname, $recursive, $upward_recursive)
	end
      end
    rescue OptionParser::ParseError => e
      STDERR.puts "#{MYNAME}: #{e}", usage
      exit 64
    end

    tasks -= $exclude_packages

    $pkgdb.sort!(tasks)

    case $service
    when :deinstall
      results = []

      result_proc = proc {
	show_results(results, 'deinstalled')
      }

      $interrupt_proc = result_proc

      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
	    if not File.writable?(contents_file)
	      warning_message "Cannot modify '#{contents_file}' to preserve shared libraries."
	      results << [pkgname, 'file unwritable']
	      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)
	    if $preserve_shlib
	      system '/bin/mv', '-f', contents_file_bak, contents_file
	    end

	    results << [pkgname, 'pkg_delete']
	    next
	  end

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

	results << [pkgname, nil]
      end

      return result_proc.call
    else
      puts tasks
    end

    return 0
  end
end

def signal_handler(sig)
  puts "\nInterrupted."
  $interrupt_proc.call if $interrupt_proc
  exit
end

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

  exit main(ARGV)
end
