#!/usr/bin/ruby -W0
# Usage examples:
#   qpp foo.pro         => ./_file.qmake
#   qpp foo/bar/        => ./_file.qmake
#
cwd = File.dirname( __FILE__ )
require 'find'
require 'ftools'
require "#{cwd}/platform.rb"

if ARGV[0] && File.file?( ARGV[0] )
  File.open( ARGV[0] ).each_line do |line|
    line.chomp!

    matches = /^\s*TEMPLATE += (.*)$/.match( line )
    if !matches.nil?
      exit if matches[1].downcase == 'subdirs'
    end

    matches = /(\s|\:|\{)VERSION\s*=\s*((\d\.){0,2}\d)$/.match( line )
    if !matches.nil? && !File.file?( "_version.h" )
      File.open( "_version.h", 'w' ) { |f| f.write( "#define VERSION \"#{matches[2]}\"\n" ) }
    end
  end
end


sources = Array.new
headers = Array.new
forms = Array.new
resources = Array.new

dir = ARGV[0]
if dir.nil?
  dir = '.'
elsif !File.directory?( dir )
  dir = File.dirname( dir )
end


def find_sources(dir)
  Find.find( dir ) do |path|
    next if path == dir # oddly neccessary
    if File.directory? path
      excludes = ['.svn', 'tests', '_build']
      case Platform::IMPL
        when :macosx then excludes << 'win'
        when :mswin, :cygwin then excludes << 'mac'
        else excludes << 'win' << 'mac'
      end
      Find.prune if excludes.include? File.basename path
      Find.prune if Dir["#{path}/*.pro"].length > 0 #don't recurse into dirs with pro files in
    elsif File.file? path
      case Platform::IMPL
        when :macosx then next if /_mac\.cpp$/.match path
        when :mswin, :cygwin then next if /_win\.cpp$/.match path
      end
      yield( path, File.extname( path ) ) unless File.basename(path) == 'EXAMPLE.cpp'
    end
  end
end


find_sources dir do |path, ext|
  path.sub! /^.\//, ''
  case ext
    when ".h"   then headers   << path
    when ".ui"  then forms     << path
    when ".qrc" then resources << path
    when ".cpp" then sources   << path
  end
end


def write_section( section, array, f )
  return if array.empty?
  f.write( section + " =" )
  array.each do |path|
    f.write( " \\\n\t" )
    f.write( path )
  end
  f.write( "\n" )
end

f = File.open( '_files.qmake', 'w' )
write_section( "SOURCES", sources, f )
write_section( "HEADERS", headers, f )
write_section( "FORMS", forms, f )
write_section( "RESOURCES", resources, f )
