 
 sync = (connection) ->
   loop
-    syncToken = SyncToken.findOne().syncToken
+    syncToken = SyncState.findOne(SYNC_TOKEN_ID).syncToken
     result = connection.call 'syncNewPackageData', syncToken
 
     if result.resetData

Fiber = Npm.require 'fibers'

SyncToken = new Mongo.Collection 'meteor.SyncToken'
Packages = new Mongo.Collection 'meteor.Packages'
Versions = new Mongo.Collection 'meteor.Versions'
Builds = new Mongo.Collection 'meteor.Builds'

        Versions.find(packageName: oldPackage.packageName).forEach (document, index, cursor) ->
          insertLatestPackage document

  lastUpdatedNewer = ->
    # We do not do anything, versions observe will handle that.
    # But we have to start the observe the first time if it is not yet running.
    startObserve() unless observeHandle

  lastUpdatedOlder = ->
    # We have to restart the versions observe.
    startObserve()

  updateLastUpdated = (newLastUpdated) ->
    if not currentLastUpdated
      currentLastUpdated = newLastUpdated
      if currentLastUpdated
        lastUpdatedNewer()
      else
        # Not currentLastUpdated nor newLastUpdated were true, we have not
        # yet started the observe at all. Let's start it now.
        startObserve()
    else if not newLastUpdated
      currentLastUpdated = null
      lastUpdatedOlder() if currentLastUpdated
    else if currentLastUpdated > newLastUpdated
      currentLastUpdated = newLastUpdated
      lastUpdatedOlder()
    else if currentLastUpdated < newLastUpdated
      currentLastUpdated = newLastUpdated
      lastUpdatedNewer()

  SyncState.find(LAST_UPDATED_ID).observe
    added: (document) ->
      updateLastUpdated document.lastUpdated?.valueOf() or null

    changed: (document, oldDocument) ->
      updateLastUpdated document.lastUpdated?.valueOf() or null

    removed: (oldDocument) ->
      updateLastUpdated null

  console.log "Latest packages observe initialized"

subscribeToPackages = ->
  connection = DDP.connect 'packages.meteor.com'

  Defaults = new Mongo.Collection 'defaults', connection
  Changes = new Mongo.Collection 'changes', connection

  connection.subscribe 'defaults', ->
    try
      SyncState.insert
        _id: SYNC_TOKEN_ID
        syncToken: Defaults.findOne().syncToken
    catch error
      throw error unless /E11000 duplicate key error index:.*SyncState\.\$_id/.test error.err

    connection.subscribe 'changes', ->
      Changes.find().observe
        added: (document) ->
          sync connection
        changed: (document, oldDocument) ->
          sync connection

Meteor.startup ->
  new Fiber ->
    latestPackagesObserve()
    subscribeToPackages()
  .run()
