#coding=utf-8

namespace :gitlab do
  desc "sync gitlab's users which lost in last sync"
  task :add_gid => :environment do
    users = User.find_by_sql("select * from users where gid is null")
    s = Trustie::Gitlab::Sync.new
    g = Gitlab.client
    logger = Logger.new('./log/add_gid.log', 'daily') #按天生成
    users.each do |user|
      begin
        us = g.get("/users?search=#{user.mail}")
        puts user.mail
        if us.blank?
          puts "55555555555555555"
          s.sync_user(user)
        else
          # 解决查询的时候出现多值的情况，比如:123@163.com和g123@163.com
          puts "66666666666666666666"
          puts user.id
          if Array === us
            us.each do |u|
              if u.email == user.mail
                user.gid = u.id
                user.save
              end
            end
          end
        end
      rescue => e
        logger.error("userid=#{user.id},mail=#{user.mail},login=#{user.login},error=#{e}")
        puts e
      end
    end
  end

  task :sync_members => :environment do
    projects = Project.all
    s = Trustie::Gitlab::Sync.new
    projects.each do |project|
      puts project.id
      s.only_members(project.first)
    end
  end
end