$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "patchfile/version"
app_path = File.expand_path(__dir__)
dir_pwd = ENV['PWD']
template_path = dir_pwd + '/app/templates'
all_template = Dir.glob(template_path+'/*/')
#if !Dir.exist?("#{ENV['PWD']}"+"/app/assets/stylesheets/lib/jquery-ui-1.12.1/")
puts "copying jquery-ui"
begin
`cp -r "#{app_path}/updatefiles/accessibility/jquery-ui-1.12.1/." "#{dir_pwd}/app/assets/stylesheets/lib/jquery-ui-1.12.1/"`
rescue
	puts "There is an error in coppying jquery-ui"
end
#end
@original_dir = Dir.pwd
`cd "#{dir_pwd}" && git add  app/templates/ app/assets  built_in_extensions.rb  config/mongoid.yml bin/ && cd "#{@original_dir}"` #using git to add modified files and to avoid git pull not working
#Add patchfile to Admin area
@patchfile_li = File.read(app_path+"/patchfile_li.txt")
@patchfile_li_choices = File.read(app_path+"/patchfile_li_choices.txt")
@file_text = File.read(dir_pwd+'/app/views/shared/_side_bar.html.erb')
if !@file_text.include?('<div class="patchfile sub-nav-block icons-megaphone">')
	@indert_index = @file_text.index('</nav>')
	@file_text.insert(@indert_index , @patchfile_li_choices)
end
if !@file_text.include?('patchfile_li')
	@indert_index = @file_text.index('<li title="<%= t(\'site_info\') %>">')
	@file_text.insert(@indert_index , @patchfile_li)
end
begin
    f = File.open(dir_pwd+'/app/views/shared/_side_bar.html.erb','w')
    f.write(@file_text)
    f.close
    puts "finish change patchfile in #{dir_pwd}/app/views/shared"
rescue
    puts "Permission denied in #{dir_pwd}/app/views/shared"
end
change_text = '<a title="{{site_title_1}}" class="navbar-brand" href="{{home_link_1}}"><img class="site-logo" src="{{logo_url_1}}" alt="Site Logo"></a><script>$(document).ready(function(){var url =$(\'.site-logo\').eq(0).attr(\'src\');if(url == "/assets/default-site-logo.png"){$(\'.navbar-brand\').eq(0).remove();};if($(\'.navbar-brand\').length == 2){$(\'.site-logo\').css(\'height\',\'auto\')};$(\'.site-logo\').eq(0).css(\'margin-right\',0);$(\'.navbar-brand\').css(\'padding-right\',0)})</script><a title="{{site_title}}" class="navbar-brand" href="{{home_link}}"><img class="site-logo" src="{{logo_url}}" alt="Site Logo"> {{site_name}}</a>'
change_text_fix = '<a title="{{site_title_1}}" class="" href="{{home_link_1}}"><img class="site-logo" src="{{logo_url_1}}" alt="Site Logo"></a><script>$(document).ready(function(){var url =$(\'.site-logo\').eq(0).attr(\'src\');if(url == "/assets/default-site-logo.png"){$(\'.navbar-brand\').eq(0).remove();};if($(\'.navbar-brand\').length == 2){$(\'.site-logo\').css(\'height\',\'auto\')};$(\'.site-logo\').eq(0).css(\'margin-right\',0);$(\'.navbar-brand\').css(\'padding-right\',0)})</script><a title="{{site_title}}" class="" href="{{home_link}}"><img class="site-logo" src="{{logo_url}}" alt="Site Logo"> {{site_name}}</a>'
change_text_fix1 = '<a title="{{site_title_1}}" class="" href="{{home_link_1}}"><img class="site-logo" src="{{logo_url_1}}" alt="Site Logo"></a><script>$(document).ready(function(){var url =$(\'.site-logo\').eq(0).attr(\'src\');if(url == "/assets/default-site-logo.png"){if($(\'.navbar-brand\').length != 0){$(\'.navbar-brand\').eq(0).remove();}else{$(\'.site-title >a\').eq(0).remove();}};if($(\'.navbar-brand\').length == 2 || $(\'.site-title >a\').length == 2){$(\'.site-logo\').css(\'height\',\'auto\')};$(\'.site-logo\').eq(0).css(\'margin-right\',0);$(\'.navbar-brand\').css(\'padding-right\',0)})</script><a title="{{site_title}}" class="" href="{{home_link}}"><img class="site-logo" src="{{logo_url}}" alt="Site Logo"> {{site_name}}</a>'
all_template.each do |folder|
  if !folder.include?('mobile')
    begin
      begin
        require 'nokogiri'
      rescue ScriptError => e
        system('gem install nokogiri -v 1.7.0.1')
        require 'nokogiri'
      end
      puts "changing header.html.erb in #{folder}/home/header.html.erb"
      if folder.split('/')[-1] != 'mobile'
        filename = folder+'home/header.html.erb'
        texts = File.read(filename)
        texts_html = Nokogiri::HTML.parse(texts)
        if texts_html.css('.navbar-brand').length == 1
          new_texts = texts.gsub(texts_html.css('.navbar-brand').to_s.gsub("%7B",'{').gsub('%7D','}'),change_text)
          File.open(filename,'w') do |f|
            f.write new_texts
          end
        elsif texts_html.css('.site-title >a').length == 1 && texts_html.css('.navbar-brand').length == 0
          new_texts = texts.gsub(texts_html.css('.site-title >a').to_s.gsub("%7B",'{').gsub('%7D','}'),change_text_fix1)
          File.open(filename,'w') do |f|
            f.write new_texts
          end
		elsif texts_html.css('.site-title >a.navbar-brand').length == 2
		  new_texts = texts.gsub(change_text,change_text_fix1)
          File.open(filename,'w') do |f|
            f.write new_texts
          end
		elsif texts.include? change_text_fix
		  new_texts = texts.gsub(change_text_fix,change_text_fix1)
          File.open(filename,'w') do |f|
            f.write new_texts
          end
        end
      end
    rescue => e
      puts "#{e.inspect}\nnot found #{folder}home/header.html.erb"
    end
  end
end
begin
  system("cp -f #{app_path}/updatefiles/application_helper.rb #{dir_pwd}/app/helpers/application_helper.rb")
rescue => e
  puts e.backtrace
end
#change_html_old = 'html.gsub("%7B%7Blogo_url_1%7D%7D",((site.site_logo_1.url.nil? ? "/assets/default-site-logo.png" : site.site_logo_1.url) rescue "/assets/default-site-logo.pngs"))'
#change_html_new = 'html.gsub("%7B%7Blogo_url_1%7D%7D",((site.site_logo_1.url.nil? ? "/assets/default-site-logo.png" : site.site_logo_1.url) rescue "/assets/default-site-logo.png"))'
#begin
#    @file_text = File.read(ENV['PWD']+'/app/helpers/application_helper.rb')
#    File.open(ENV['PWD']+'/app/helpers/application_helper.rb_new','w+') do |f|
#      f.chmod 0777
#      if @file_text.include?(change_html_old)
#        @file_text = @file_text.gsub(change_html_old,change_html_new)
#      elsif (!@file_text.include?(change_html_old) && !@file_text.include?(change_html_new))
#        insert_index = @file_text.index('html.gsub("%7B%7Blogo_url%7D%7D"')
#        @file_text.insert(insert_index,change_html_new+"\n")
#      end
#      f.write(@file_text)
#    end
#    system("cp #{ENV['PWD']+'/app/helpers/application_helper.rb_new'} #{ENV['PWD']+'/app/helpers/application_helper.rb'}")
#    puts "finish change application_helper.rb in #{ENV['PWD']}/app/helpers/"
#rescue => e
#    puts "Permission denied in #{ENV['PWD']}/app/helpers/application_helper.rb"
#end
begin
  require 'mongoid'
  require "#{dir_pwd}/app/models/site"
  site_first = Site.first
  if site_first[:display_title_in_frontend].nil?
    puts 'close display double title in frontend'
    site_first.update_attributes(:display_title_in_frontend=>false) 
  end
rescue Exception => e
  puts e
  puts 'unable to close title display in frontend.'
end
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
  s.name        = "patchfile"
  s.version     = Patchfile::VERSION
  s.authors     = ["Ruling Digital"]
  s.email       = ["orbit@rulingcom.com"]
  s.homepage    = "http://www.rulingcom.com"
  s.summary     = "Patch_file for Orbit"
  s.description = "Patch_file for Orbit"
  s.license     = "MIT"

  s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
  s.test_files = Dir["test/**/*"]
end
