require "mongo"
require "../core/devops-config"

class UsersPermissionsUpdater
  attr_reader :users_collection

  def initialize
    DevopsConfig.read
    config = DevopsConfig.config

    db = config[:mongo_db] || "devops"
    host = config[:mongo_host] || "localhost"
    port = config[:mongo_port] || 27017
    user = config[:mongo_user]
    password = config[:mongo_password]

    puts
    puts "Initialized updater for db '#{db}' located on host '#{host}'"

    @db = Mongo::MongoClient.new(host, port).db(db)
    @db.authenticate(user, password)
    @users_collection = @db.collection('users')
  end

  def admins
    users_collection.find('privileges.server' => 'rwx')
  end

  def readers
    users_collection.find('privileges.server' => 'r')
  end

  def set_priveleges_to_users(users, privilege_value)
    ids = users.to_a.map {|u| u['_id']}
    puts "users: #{ids.join(', ')}"

    ids.each do |id|
      @users_collection.update(
        {"_id" => id},
        {
          "$set" => {
            "privileges.stack" => privilege_value,
            "privileges.stack_template" => privilege_value
          }
        }
      )
    end

  end

end

updater = UsersPermissionsUpdater.new
updater.set_priveleges_to_users(updater.admins, 'rwx')
puts "Admin privileges updated"

updater.set_priveleges_to_users(updater.readers, 'r')
puts "Readers privileges updated"
