#!/usr/bin/env ruby

require 'date'

def get_deprecated(makefile)
	File.readlines(makefile).each do |line|
		if line =~ /\ADEPRECATED.*[0-9]+/
			return line.strip.split(/\s+/).last
		end
	end
	return nil
end

def get_expiration_date(makefile)
	File.readlines(makefile).each do |line|
		if line =~ /\AEXPIRATION_DATE.*[0-9]+/
			return line.strip.split(/\s+/).last
		end
	end
	return nil
end

def add_deprecation(makefile, date, message)
	lines = File.readlines makefile
	# Order according to porters handbook:
	#   MAINTAINER COMMENT LICENSE LICENSE_COMB LICENSE_GROUP LICENSE_NAME LICENSE_TEXT LICENSE_FILE LICENSE_PERMS LICENSE_DISTFILES
	nos = []
  nos << (lines.index{|l| l =~ /\AMAINTAINER.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ACOMMENT.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_COMB.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_GROUP.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_NAME.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_TEXT.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_FILE.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_PERMS.?=.*[A-Za-z]+/} || 0)
  nos << (lines.index{|l| l =~ /\ALICENSE_DISTFILES.?=.*[A-Za-z]+/} || 0)

  # Position in Makefile to put deprecated after
    no  = nos.sort.last

  current_date = get_expiration_date(makefile)
  if current_date
    d_date = Date.parse(date)
    d_curr = Date.parse(current_date)

    if d_curr <= d_date
      puts  "#{makefile} is already marked for #{current_date} -- not adding #{date}"
      return
    end

    puts  "#{makefile} is already marked for #{current_date} -- adding newer #{date}"
  end

  puts "adding EXPIRATION_DATE=#{date} to #{makefile}"
  lines.insert no+1, "\nDEPRECATED=\t\t#{message}\nEXPIRATION_DATE=\t#{date}\n"

	File.open(makefile,'wb'){|f| f.write(lines.join)}
end

args = ARGV
if args.length < 3
  puts "no arguments given: required <date> <message> <port1 <ports2,.>>]"
	return 1
end


date = args.shift
message = args.shift

args.each do |arg|
	makefile = File.join arg, "Makefile"
	next unless File.directory?(arg)
    unless File.exist?(makefile)
        puts "skipping #{arg}"
        next
    end

    add_deprecation makefile, date, message
end
