#!/usr/bin/env ruby
#
# de-pkg-comment - converts pkg-comment to COMMENT
# (public domain)
#
# Usage:
#   de-pkg-comment portdir ...
#
# Notes:
#   - Local changes may be backed out and the previous file is renamed
#     to .#* if conversion fails.  
#   - It requires a port have a MAINTAINER line.
#   - It does not touch master/slave ports automatically; just shows
#     some hints.
#   - Do not commit resulted files without checking the diffs.
#
# MAINTAINER=	knu@FreeBSD.org
#
# $FreeBSD: ports/Tools/scripts/de-pkg-comment,v 1.2 2003/02/21 13:12:02 knu Exp $
#

begin
  require 'features/ruby18'
rescue LoadError; end

if ARGV.empty?
  STDERR.puts "usage: #{$0} portdir ..."
  exit 64
end

def error(message)
  STDERR.puts("#{$dir}: #{message}")
end

def info(message)
  STDOUT.puts("#{$dir}: #{message}")
end

def backout(message)
  error(message)
  info("Backing out all modifications.")
  system 'cvs', '-Q', 'up', '-CdP'
end

def cvs_up(*files)
  system *['cvs', '-q', 'up', '-dP', *files]
end

def cvs_rm(*files)
  system *['cvs', '-Q', 'rm', '-f', *files]
end

ARGV.each { |$dir|
  if !File.directory?($dir)
    error("Not a directory.")
    next
  end

  Dir.chdir($dir) {
    if !File.directory?('CVS')
      error("Not a CVS working directory.")
      next
    end

    info("Running cvs update")
    cvs_up()

    makefile = 'Makefile'

    if !File.exist?(makefile)
      error("No Makefile is found.")
      next
    end

    commentfile = `make -V COMMENTFILE`.chomp

    if !File.exist?(commentfile)
      error("No need to convert.")
      next
    end

    comment = nil
    commentfile_defined = false
    maintainer_defined = false

    info("Modifying #{makefile}")

    open(makefile, 'r+') { |rw|
      contents = []

      rw.each { |line|
	contents << line

	case line
	when /^MAINTAINER\s*(\??=)/
	  maintainer_defined = true

	  assign = $1

	  if assign == '?='
	    info("Looks like a master port.  Please check for slave ports.")
	  end

	  open(commentfile) { |f|
	    comment = f.gets.strip
	    quoted_comment = comment.gsub(/#/, '\\#').gsub(/\$/, '$$')
	    contents << "COMMENT#{assign}\t#{quoted_comment}\n"
	  }
	when /^COMMENTFILE\s*([?!:]?=)/
	  info("COMMENTFILE is defined.  Please check out and edit manually.")
	  commentfile_defined = true
	when /^MASTERDIR\s*([?!:]?=)/
	  masterport = File.expand_path(`make -V MASTERDIR`.chomp)
	  masterport.sub!(%r".*(?:^|/)([^/]+/[^/]+)$", '\1')

	  info("Looks like a slave port.  Please look into the master port (#{masterport}) also.")
	end
      }

      rw.rewind
      rw.puts contents
    }

    if !maintainer_defined
      backout("No MAINTAINER line is found!")
      next
    end

    newcomment = `make -V COMMENT`.chomp

    if newcomment != comment
      backout("Failed to convert!")
      next
    end

    unless commentfile_defined
      info("Removing #{commentfile}")
      cvs_rm(commentfile)
    end

    info("Running cvs update again")
    cvs_up()

    info("Done.")
  }
}
