<commit_before>log = ->
  console.log '[handlers:memberremoved]', arguments...

module.exports = memberRemoved = ({ group, member, requester }) ->

  # Ignore kicks for guests and koding
  return  if group.slug in ['guests', 'koding']

  # Find the reason of removal
  reason = if member.getId().equals requester.getId() then 'leave' else 'kick'

  member.fetchUser (err, user) ->
    return log 'Failed to fetch user:', err  if err or not user

    userId = user.getId()

    JMachine = require '../machine'
    JMachine.some
      'provider'  : { $nin: ['koding', 'managed'] }
      'users.id'  : userId
      'groups.id' : group.getId()
    , {}
    , (err, machines = []) ->

      return log 'Failed to fetch machines:', err  if err

      machines.forEach (machine) ->

        owner = no # Make sure the user is owner of the machine
        for u in machine.users
          if u.owner and u.sudo and userId.equals u.id
            owner = yes
            break

        machine.removeUsers { targets: [ user ] }, (err) ->
          log "Couldn't remove user from users:", err  if err
          return  if not owner or reason is 'leave'

          requester.fetchUser (err, admin) ->
            return log 'Failed to fetch requester:', err  if err or not admin

            machine.addUsers { targets: [ admin ], asOwner: yes }, (err) ->
              return log 'Failed to change ownership:', err  if err<commit_msg>MemberRemovedHandler: use queue for handling the flow<commit_after>{ daisy } = require 'bongo'

log = ->
  console.log '[handlers:memberremoved]', arguments...

checkOwnership = (machine, user) ->

  userId = user.getId()
  owner  = no

  for u in machine.users
    if u.owner and u.sudo and userId.equals u.id
      owner = yes
      break

  return owner


module.exports = memberRemoved = ({ group, member, requester }) ->

  # Ignore kicks for guests and koding
  return  if group.slug in ['guests', 'koding']

  # Find the reason of removal
  reason = if member.getId().equals requester.getId() then 'leave' else 'kick'

  memberJUser    = null
  requesterJUser = null
  memberMachines = []

  queue  = [

    ->
      member.fetchUser (err, user) ->
        return log 'Failed to fetch member:', err  if err or not user
        memberJUser = user
        queue.next()

    ->
      if reason is 'leave'
        requesterJUser = memberJUser
        queue.next()
      else
        requester.fetchUser (err, user) ->
          if err or not user # even we fail to fetch JUser of admin somehow
                             # we don't need to cut the process here, we can
                             # continue with members info, and remove
                             # all the resources belongs to the user ~ GG
            log 'Failed to fetch requester:', err
            requesterJUser = memberJUser
          else
            requesterJUser = user
          queue.next()

    ->
      JMachine = require '../machine'
      JMachine.some
      # Not sure about this, open for debate, should we remove user from
      # managed vms and koding vms if somehow s/he has one in this group ~ GG
      # 'provider'  : { $nin: ['koding', 'managed'] }
        'users.id'  : memberJUser.getId()
        'groups.id' : group.getId()
      , {}
      , (err, machines = []) ->

        log 'Failed to fetch machines:', err  if err
        memberMachines = machines
        queue.next()

    ->
      memberMachines.forEach (machine) ->
        # Make sure the user is owner of the machine
        owner = checkOwnership machine, memberJUser

        machine.removeUsers { targets: [ memberJUser ] }, (err) ->
          log "Couldn't remove user from users:", err  if err
          return  if not owner or reason is 'leave'

          # Move machine ownership to the admin who kicked the member
          machine.addUsers {
            targets: [ requesterJUser ], asOwner: yes
          }, (err) ->
            log 'Failed to change ownership:', err  if err

      queue.next()
  ]

  daisy queue
{'fraction_non_alphanumeric': 0.10184262948207172, 'fraction_numerical': 0.0, 'mean_word_length': 2.027128862094951, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5530825', 'n_tokens_mistral': 1151, 'n_tokens_neox': 1125, 'n_words': 417}