class SiteConstruct
  include Mongoid::Document
  include Mongoid::Timestamps
  def self.server_types
    SiteServer.where(:active.ne=>false).map{|s| s.server_name}
  end
  SITE_TYPES = ["School","Gravity"]
  field :enable_redirect_default_domain, type: Integer, default: 0 #0 => use default, 1 => disable, 2 => enable
  field :default_domain_idx, type: Integer, default: -1 #-1 present use default
  field :rails_env, type: String, :default => "development"
  field :server_type
  field :site_name
  field :domain_name
  field :nginx_file
  field :db_name
  field :port, type: Array, :default => ["80"]
  field :path
  field :site_type
  field :school_name
  field :user_id
  field :constructed, type: Boolean, :default => false
  field :status, type: String, :default => ""
  field :infos, type: Array, :default => []
  field :hidden, type: Boolean, :default  => false
  field :copy_id
  field :only_copy_installed_module, type: Boolean, :default  => false
  field :redirect_to_https, type: Boolean, :default => false
  field :cert_ver_added_text
  field :cert_ver_file_content
  field :cert_ver_location_path
  field :super_user_changed, type: Boolean, type: false
  field :removed_super_users, type: Array, default: []
  belongs_to :site_cert
  has_many :site_super_users, :autosave => true, :dependent => :destroy
  accepts_nested_attributes_for :site_super_users, :allow_destroy => true
  after_initialize do |record|
    unless record.new_record?
      save_flag = false
      if record.status.nil?
        record.status = ""
        save_flag = true
      end
      if record.infos.nil?
        record.infos = []
        save_flag = true
      end
      if record.nginx_file.nil?
        record.nginx_file = "/etc/nginx/orbit_sites/"+record.site_name.to_s
        save_flag = true
      end
      if record.path.nil?
        dir_path = ((record.site_type == "School" && !record.school_name.blank?) ? "school_sites/#{record.school_name}" : "orbit_sites")
        record.path = "/home/rulingcom/#{dir_path}"
        save_flag = true
      end
      if record["port"].class == String
        record["port"] = Array(record["port"])
        save_flag = true
      end
      if save_flag && !@skip_callback
        @skip_callback = true
        record.save(:validate=>false)
      end
      @skip_callback = false
    end
  end
  def check_super_user_changed
    self.update(:super_user_changed => (self.site_super_users.where(:is_changed=>true).count != 0 || self.removed_super_users.count != 0))
  end
  def generate_nginx_text(old_nginx_text="")
    sock_text = "upstream #{self.get_site_name}_sock {\n"+
              "  server unix:#{self.full_site_path}/tmp/unicorn.sock;\n"+
              "}\n"
    all_ports = self.port.uniq
    server_blocks = []
    port_server_blocks_relation = {}
    if old_nginx_text.present?
      all_blocks = parse_nginx_text_to_server_blocks(old_nginx_text,true)
      server_blocks = all_blocks.select{|s| s.match(/\A[\s\r\n]*server\s*{/)}
      upstream_block = all_blocks.select{|s| s.match(/\A[\s\r\n]*upstream/)}.first rescue nil
      if upstream_block.present?
        sock_text = upstream_block + "\n"
      end
      server_blocks.each_with_index do |server_block, i|
        tmp_ports = server_block.gsub(/(^|\s+|;)listen\s+(\d+)/).map{$2}
        tmp_ports.each do |port|
          port_server_blocks_relation[port] = i
        end
      end
    end
    all_ports.each do |port|
      tmp = port_server_blocks_relation[port]
      if tmp.nil?
        port_server_blocks_relation[port] = 0
      end
    end
    nginx_text = sock_text + port_server_blocks_relation.map{|port,i|
      if server_blocks[i].present?
        generate_server_block(port,server_blocks[i])
      else
        generate_server_block(port,server_blocks[0])
      end
    }.join("\n").gsub("\n", '\n')
  end
  def match_exact_index(text,match_character,level=1)
    text.enum_for(:scan,/(?:[^#{match_character}])#{match_character}{#{level}}(?!#{match_character})/m).map { offset_index=::Regexp.last_match.to_s.index(match_character);::Regexp.last_match.offset(0).first + offset_index}
  end
  def parse_nginx_text_to_server_blocks(nginx_text,get_all_blocks=false,level=1)
    num = 1
    nginx_text_tmp = nginx_text.gsub(/({|})/m){|ff| res = ff;((ff == '{') ? (res = ff * num;num = num + 1) : (num = num - 1;res = ff * num;)); res}
    end_indices = match_exact_index(nginx_text_tmp,'}',level)
    start_indices = match_exact_index(nginx_text_tmp,'{',level)
    start_indices = start_indices.map.with_index{|i, j| (i - nginx_text_tmp[(j == 0 ? 0 : start_indices[j-1])...i].reverse.index(/(}|;|\n)/m)) rescue 0}
    all_blocks = (0...end_indices.count).map{|i| nginx_text_tmp[start_indices[i]..end_indices[i]]}
    all_blocks = all_blocks.map{|s| s.gsub(/[{}]+/){|ff| ff[0]}.strip}
    if get_all_blocks
      all_blocks
    else
      server_blocks = all_blocks.select{|s| s.match(/\A[\s\r\n]*server\s*{/)}
      server_blocks
    end
  end
  def generate_server_block(port,old_server_block="")
    if port.blank?
      port = "80"
    else
      port = port.to_s
    end
    default_domain = get_default_domain
    redirect_default_text = get_redirect_default_text(port, default_domain)
    port_text = port
    if port.to_i == 443
      if self.site_cert.nil?
        return ""
      end
      port_text += " ssl"
    end
    domain_name_str = self.domain_name
    if default_domain.present?
      domain_name_str = ((domain_name_str.split(/\s+/) - [default_domain]) + [default_domain]).join(" ")
    end
    if old_server_block.present?   
      new_server_block = old_server_block.gsub('\n',"\n").gsub(/(listen\s+)[^;]+/){|ff| "#{$1}#{port_text}"}
      if port_text == "80"
        new_server_block = new_server_block.gsub(/^(?:(?!{|}).)*#\s*managed by Certbot(\n|$)/,'')
      else
        if self.site_cert && !(self.site_cert.is_certbot)
          new_server_block = new_server_block.gsub(/[ \t]*#\s*managed by Certbot/,'')
        end
      end
      new_server_block = new_server_block.gsub(/(server_name\s+)[^;]+/m){|ff| "#{$1}#{domain_name_str}"}
      new_server_block = new_server_block.gsub(/\s*ssl_certificate[^;]+;/,'')
      level_2_block = parse_nginx_text_to_server_blocks(old_server_block,true,2)
      get_redirect_block = level_2_block.select{|t| t.match(/\s*return\s+30[12]\s+https:\/\/\$host\$request_uri\s*;/)}
      get_redirect_to_default_block = level_2_block.select{|t| t.match(/\s*return\s+30[12]\s+http(s|):\/\/[^\$]+\$request_uri\s*;/)}
      location_app_block = level_2_block.select{|t| t.match(/location\s+@app/)}
      if get_redirect_block.count > 0
        get_redirect_block.each do |redirect_block|
          new_server_block = new_server_block.gsub(redirect_block,'')
        end
      end
      if get_redirect_to_default_block.count > 0
        get_redirect_to_default_block.each do |redirect_block|
          new_server_block = new_server_block.gsub(redirect_block,'')
        end
      end
      if location_app_block.count > 0
        location_app_block = location_app_block.map do |app_block|
            new_app_block = app_block.gsub(/proxy_set_header\s+X-Forwarded-Proto\s+https\s*;/,"")
            new_server_block = new_server_block.gsub(app_block,new_app_block)
            new_app_block
        end
      end
      if port == "443"
        new_server_block = new_server_block.gsub(/(listen\s+)[^;]+;/){|ff| ff + "\n\n  ssl_certificate #{self.cert_file_remote_store_path};\n\n  ssl_certificate_key #{self.private_key_remote_store_path};\n\n"}
        location_app_block.each do |app_block|
            new_app_block = app_block.gsub(/proxy_set_header\s+Host\s+\$http_host\s*;/){|ff| ff + "\n    proxy_set_header   X-Forwarded-Proto  https;"}
            new_server_block = new_server_block.gsub(app_block,new_app_block)
        end
      else
        if self.redirect_to_https && !self.site_cert.nil?
          new_server_block = new_server_block.sub(/(listen\s+)[^;]+;[\s\r\n]*/){|ff| ff + "  if ($host ~ (#{self.site_cert.domain_names.map{|s| '^'+s.gsub('.','\.').gsub('*','[^.]*').gsub(',','')}.join('|')}) ) {\n"+
                                                                                      "    return 301 https://$host$request_uri;\n"+
                                                                                      "  }\n"}
        end
      end
      if redirect_default_text.present?
        new_server_block = new_server_block.sub(/\s*root/){|ff| redirect_default_text + ff}
      end
      new_server_block = new_server_block.gsub(/[\s]+\n/,"\n\n").gsub(/\n{3,}/,"\n\n").gsub("\n", '\n')
    else
      new_server_block = "server {\n"+
        "  listen #{port_text};\n\n"+
        (port == "443" ? "  ssl_certificate #{self.cert_file_remote_store_path};\n\n"+
                        "  ssl_certificate_key #{self.private_key_remote_store_path};\n\n"+
                        ((self.redirect_to_https && !self.site_cert.nil?) ? "  if ($host ~ (#{self.site_cert.domain_names.map{|s| '^'+s.gsub('.','\.').gsub('*','[^.]*').gsub(',','')}.join('|')}) ) {\n"+
                        "    return 301 https://$host$request_uri;\n"+
                        "  }\n" : '') : '')+
        redirect_default_text +
        "  root #{self.full_site_path}/public;\n\n"+
        "  server_name #{domain_name_str};\n\n"+
        "  client_max_body_size 500m;\n\n"+
        "  location / {\n"+
        "    try_files $uri $uri/index.html $uri.html @app;\n"+
        "  }\n\n"+
        "  location @app {\n"+
        "    proxy_redirect     off;\n"+
        "    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;\n"+
        "    proxy_set_header   Host  $http_host;\n"+
        (port == "443" ? "    proxy_set_header X-Forwarded-Proto https;\n" : "")+
        "    proxy_connect_timeout   360;\n"+
        "    proxy_pass http://#{self.get_site_name}_sock;\n"+
        "  }\n"+
        "}"
        new_server_block.gsub("\n", '\n')
    end
  end
  def display_port
    self.port.map{|port| "<a href=\"#{get_domain_name(port)}\" title=\"#{port}\" target=\"_blank\">#{port}</a>"}.join("<br>").html_safe
  end
  def get_port(idx=0)
    self.port[idx] rescue "80"
  end
  def full_site_path
    return "#{self.get_path}/#{self.get_site_name}"
  end
  def cert_file_remote_store_path
    site_cert = self.site_cert
    if site_cert.source_paths.present? && site_cert.source_paths.count == 2
      site_cert.source_paths[0]
    else
      "#{self.full_site_path}/ssl_certs/#{site_cert.id}/#{site_cert["cert_file"]}"
    end
  end
  def private_key_remote_store_path
    site_cert = self.site_cert
    if site_cert.source_paths.present? && site_cert.source_paths.count == 2
      site_cert.source_paths[1]
    else
      "#{self.full_site_path}/ssl_certs/#{site_cert.id}/#{site_cert["private_key"]}"
    end
  end
  def get_path
    return self.path.to_s.gsub(" ","\\ ")
  end
  def get_site_name
    return self.site_name.to_s.gsub(" ","\\ ")
  end
  def get_domain_name(port=nil)
    scheme = ""
    extra_port = ""
    port = self.get_port if port.nil?
    if port == "443"
      scheme = "https://"
    else
      scheme = "http://"
      if port != "80"
        extra_port = ":#{port}"
      end
    end
    return (scheme + self.domain_name.split(" ").first + extra_port)
  end
  def site_server
    SiteServer.where(server_name: self.server_type).first
  end
  def get_default_domain(force_get=false)
    custom_default_domain_name = ""
    domain_names = domain_name.strip().split(" ")
    if default_domain_idx == -1
      site_server.default_domain_names.each do |default_domain_name|
        default_domain_name = ::Regexp.new("\\A"+default_domain_name.gsub(".","\\.").gsub("*","[^.]*"))
        custom_default_domain_name = domain_names.select{|n| n.match(default_domain_name) }.first
        break if custom_default_domain_name.present?
      end
      if force_get && custom_default_domain_name.blank?
        custom_default_domain_name = domain_names[0]
      end
    else
      custom_default_domain_name = domain_names[default_domain_idx]
    end
    custom_default_domain_name
  end
  def get_enable_redirect_default_domain
    (self.enable_redirect_default_domain == 0 ? site_server.enable_redirect_default_domain : ((self.enable_redirect_default_domain - 1) == 1) rescue false)
  end
  def default_enable_redirect_default_domain
    site_server.enable_redirect_default_domain rescue false
  end
  def get_redirect_default_text(port=80,default_domain=nil)
    port = port.to_i
    is_enable = get_enable_redirect_default_domain
    scheme = (port == 443 ? "https" : "http")
    port_text = ((port == 80 || port == 443 || port.blank?) ? "" : ":#{port}")
    text = ""
    if is_enable
      default_domain = get_default_domain if default_domain.nil?
      if default_domain.present?
        text = "\n\n  if ($host !~* (^#{default_domain.gsub('.','\.')}$) ) {\n"+
               "    return 302 #{scheme}://#{default_domain}#{port_text}$request_uri;\n"+
               "  }\n\n"
      end
    end
    text
  end
end