#!/usr/bin/env ruby
# strip unneeded build dependencies from golang source codes

def find_build_directory()

        path = "/home/abuild/rpmbuild/SOURCES"
        #path = `pwd`.gsub(/\n/,'')

        specfile = Dir.glob(path + "/*.spec")[0]

        pkgname = ""

        File.open(specfile) do |f|

                f.each_line do |l|

                       build_found = 0

                        if l.index("Source:") then

                                unless l.index("%{name}") then

                                        pkgname = l.gsub(/Source:/,'').lstrip!.chomp!.gsub(/^.*\//,'').gsub(/-%.*$/,'')

                                        build_found = 1

                                end

                        end

                        if (build_found == 0 && l.index("Name:")) then

                                pkgname = l.gsub(/Name:/,'').lstrip!.chomp!.gsub(/^(go|golang)-/,'')

                        end

                end

        end

        build = Dir.glob("/home/abuild/rpmbuild/BUILD/*#{pkgname}*")[0]
        #build = Dir.glob(path + "/*#{pkgname}*")[0]

        return build

end

def all_file(dir="",result=nil)

        result = [] unless result

        Dir.entries(dir).each do |d|

                unless (d == "." || d == ".." || d.index("example") || d.index("test")) then

                        if File.directory?("#{dir}/#{d}") then

                                all_file("#{dir}/#{d}",result)

                        else

                                if ( d.index(".go") && ! d.index(/(test|example)/) ) then

                                        result << "#{dir}/#{d}"

                                end

                        end

                end

        end

        return result

end

def get_commandline_options()

	options = []

	$*.each do |o|

		options << o

	end

	return options

end

def delete_line(filepath="",line="")

	require 'fileutils'

	newpath = filepath + ".new"

	File.open(filepath,'r') do |f1|

		File.open(newpath,'w') do |f2|

			f1.each_line do |l|

				f2.write(l) unless l.index(line)

			end

		end

	end

	FileUtils.mv newpath, filepath

end

def strip_unneed_dependency()

        build = find_build_directory()

        source = all_file(build)

	options = get_commandline_options()

	options.each do |opt|

		source.each do |s|

			if File.readlines(s, :encoding => "UTF-8").grep(/#{opt}/).size > 0

				delete_line(s,opt)	

			end

		end

	end

end

strip_unneed_dependency()
