#! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
# Extract copyright holders.
# Author:   Daigo Moriwaki <beatles@sgtpepper.net>
# Copyright (c) 2005 Daigo Moriwaki
#               2015 Youhei SASAKI
# License:  GNU GENERAL PUBLIC LICENSE Version 2 or later.
#

require 'find'

class Theme < Struct.new(:name, :author, :copyright, :access, :license)
  def has_license?
    license && license.length > 0
  end

  def has_author?
    author && author.length > 0
  end

  def to_s
    s = ""
    if has_license?
      s << "Files: #{name}/*\n"
      if  copyright
        c = copyright.strip.gsub(/\s*Copyright\s*/i,"Copyright: ")
        c = c.gsub(/\s*Theme Double\s*/,'')
        c = c.gsub(/\* renameCopyright: zoe>>>Nana/i,'')
        c = c.gsub(/\s*\(C\)\s*/i, " ").gsub(/by /,"").gsub(/All Rights Reserved\./i,'')
        s << c + "\n"
      elsif author
        s << "Copyright: #{author.strip.gsub(/Author: /,'')}\n"
      end
      if license.strip =~ /.*GPL$/
        s << "License: GPL-2.0+\n"
      else
        s << license.strip + "\n"
      end
      s << "\n"
    else
      s << "#{name}\n"
      s << "### NO LICENSE ###\n"
      s << "\n"
    end

    s
  end

  def valid?
    has_license?
    has_author?
  end
end


def parse_readme(f)
  theme = Theme.new
  theme.name = File.basename(File.dirname(f))
  File.open(f).read.each_line do |line|
    case line.strip!
    when /author/i
      theme.author = line
    when /copyright/i
      theme.copyright = line
    when /access/i
      theme.access = line
    when /license/i
      theme.license = line
    end
  end
  theme
end


def main
  themes = []
  errors = []
  puts Find.find(File.expand_path('../../', __FILE__)) {|f|
    themes << parse_readme(f)  if f =~ /README$/
  }
  themes.uniq!
  themes.sort! {|a,b| a.name <=> b.name}
  erros = themes.select {|theme| not theme.valid?}
  themes -= errors
  themes.each {|t| print t.to_s}
  if errors.length > 0
    puts "### ERRORS ###"
    p errors
  end
end


main if __FILE__ == $0
