 initQuery = ->
   t = setInterval ->
     do queryServers
-  , 1000 * 60 * queryInterval
+  , queryInterval
 
   do queryServers
 
+###
+iterate through the staging servers and hand off to be checked
+###
 queryServers = ->
   console.log '\nquerying staging servers'
 
   newResults = {}
+  serverCount = serverList.length
 
   _.each serverList, (server) ->
     queryServer server, (currentBranch) ->
-      newResults[server] = currentBranch
-
-      if _.keys(newResults).length is serverList.length
-        console.log '\n'
-        console.log newResults
+      if currentBranch
+        newResults[server] = currentBranch
+      else
+        serverCount--;
+
+      if _.keys(newResults).length is serverCount
+        do printLineBreak
+        devLog newResults
 
         compareResults newResults
 
+###
+ask each staging server what branch they're running
+###
 queryServer = (server, callback = ->) ->
   # console.log '\nquerying server:\n' + server
-
-  conn = new SSH()
-
-  conn.on 'ready', ->
-    conn.shell 'echo "test"', (err, stream) ->
-      throw err if err
-
-      output = []
-
-      stream.stderr.on 'data', (data) ->
-        console.error 'STDERR: ' + data
-
-      stream.on 'data', (data) ->
-        data = data.toString('utf8').replace /\s/g, ''
-
-        # remove
-        return false if data.length < 2 or /^\[/.test data
-
-        # if the following command gets lumped in with the current line's output, cut it out
-        data = data.split(/\[/)[0] if /\[/.test data
-
-        output.push data
-
-      stream.on 'close', ->
-        do conn.end
-
-        # console.log '\n' + server + ' responded:\n' + currentBranch
-
-        callback do output.pop
-
-      stream.end 'cd $(cat /etc/httpd/conf.d/pinnacle.conf | grep -m 1 DocumentRoot | sed s/DocumentRoot// | sed s/\\"//g)\ngit rev-parse --abbrev-ref HEAD\nexit\n'
-
-  conn.connect
-    host: server
-    port: 22
-    username: 'ec2-user'
-    privateKey: file.readFileSync '/Users/bradmallow/Documents/keys/dops-dev.pem'
-
+  maxAttempts   = 10
+  connAttempts  = 0
+
+  # test for forward or backward slashes, aka things that shouldn't be in a branch
+  # if found, rerun branch check
+  validateResponse = (response) ->
+    response = if response.length then response.pop().split('Pinnaclebranch:')[1].split('Contrabranch:')[0] else 'logout'
+
+    unless /\\|\/|logout|HEAD/.test response
+      callback response
+    else if connAttempts >= maxAttempts
+      callback false
+    else
+      do printLineBreak
+      console.info 'uh-oh, SSH branch check ' + connAttempts + ' of ' + maxAttempts + ' for server ' + server + ' returned bad data\ntrying again'
+
+      do doQueryServer
+
+  doQueryServer = ->
+    connAttempts++;
+
+    conn = new SSH()
+
+    conn.on 'ready', ->
+      conn.shell 'echo "test"', (err, stream) ->
+        throw err if err
+
+        output = []
+
+        stream.stderr.on 'data', (data) ->
+          console.error 'STDERR: ' + data
+
+        stream.on 'data', (data) ->
+          data = data.toString('utf8').replace /\s/g, ''
+
+          # remove
+          return false if data.length < 2 or /^\[|Nosuchfileordirectory/.test data
+
+          # if the following command gets lumped in with the current line's output, cut it out
+          data = data.split(/\[/)[0] if /\[/.test data
+
+          output.push data if /Pinnaclebranch/.test data
+
+        stream.on 'close', ->
+          do conn.end
+
+          # do printLineBreak
+          # devLog server + ' responded:'
+          # do printLineBreak
+          # devLog currentBranch
+
+          validateResponse output
+
+        stream.end 'cat /tmp/' + server.split('.')[1].toUpperCase() + '_CURRENT_BRANCHES\nexit\n'
+
+    conn.connect
+      host: server
+      port: 22
+      username: 'ec2-user'
+      privateKey: file.readFileSync '/Users/bradmallow/Documents/keys/dops-dev.pem'
+
+  # initial server query
+  do doQueryServer
+
+###
+check to see if any servers have changed
+###
 compareResults = (newResults) ->
   console.log '\ncomparing results'
 

  callbackCheck = (type) ->
    complete[type] = true

    do callback if complete.branch and complete.pull and complete.labels and complete.milestone

  newServerData[server] =
    server    : server
    property  : server.split('.')[1]
    branch    :
      name      : branch

  queryBranch newServerData, server, branch, ->
    callbackCheck 'branch'

  queryPull newServerData, server, branch, ->
    callbackCheck 'pull'

    if newServerData[server].pull.number
      queryLabels newServerData, server, newServerData[server].pull.number, ->
        callbackCheck 'labels'

    else
      callbackCheck 'labels'

  queryMilestone newServerData, server, branch, activeMilestones, ->
    callbackCheck 'milestone'

queryBranch = (newServerData, server, branch, callback = ->) ->
  pinnacle.branch branch, (err, data, headers) ->
    if err
      if err.statusCode is 404
        newServerData[server].branch = _.extend newServerData[server].branch or {},
          name: branch
          open: false

      do callback

    else
      # console.log '\n'
      # console.log data

      newServerData[server].branch = _.extend newServerData[server].branch or {},
        name: data.name
        link: data._links.html
        open: true

      newServerData[server].last_commit = _.extend newServerData[server].last_commit or {},
        date: data.commit.commit.author.date
        message: data.commit.commit.message

      newServerData[server].author = _.extend newServerData[server].author or {},
        name: data.commit.author.login
        link: data.commit.author.html_url
        pic: data.commit.author.avatar_url

      do callback

queryPull = (newServerData, server, branch, callback = ->) ->
  pinnacle.prs
    page      : 1
    per_page  : 100
    head      : 'Thrillist:' + branch
    state     : 'all'
  , (err, data, headers) ->
    if data and data.length
      data = data[0]

      # console.log '\n'
      # console.log data

      newServerData[server].branch = _.extend newServerData[server].branch or {},
        name : data.head.ref
        link : 'https://github.com/Thrillist/Pinnacle/tree/' + data.head.ref

      newServerData[server].pull = _.extend newServerData[server].pull or {},
        open    : if data.state is 'open' then true else false
        merged  : if data.merged_at then true else false
        name    : data.title
        link    : data._links.html.href

      newServerData[server].author = _.extend newServerData[server].author or {},
        name  : data[if data.assignee then 'assignee' else 'user'].login
        link  : data[if data.assignee then 'assignee' else 'user'].html_url
        pic   : data[if data.assignee then 'assignee' else 'user'].avatar_url

    else
      newServerData[server].pull = false

    do callback

queryLabels = (newServerData, server, number, callback = ->) ->
  # query for a specific pull request's labels
  issue = github.issue githubRepo, number

  issue.info (err, data, headers) ->
    if err
      console.error err

      newServerData[server].pull.labels = false

    else if data
      # console.log '\n'
      # console.log data

      newServerData[server].pull.labels = []

      _.each data.labels, (label) ->
        newServerData[server].pull.labels.push
          link  : label.url.replace('api.github.com/repos', 'github.com').replace('+', '%20')
          color : '#' + label.color
          name  : label.name

    do callback

queryMilestone = (newServerData, server, branch, activeMilestones, callback = ->) ->
  if activeMilestones[branch]
    pinnacle.issues
      page      : 1
      per_page  : 100
      milestone : activeMilestones[branch]
      state     : 'all'
    , (err, data, headers) ->
      if data
        # console.log '\n'
        # console.log data[0]

      else
        newServerData[server].milestone = false

      do callback

  else
    newServerData[server].milestone = false

    do callback


do init
    res.header 'Access-Control-Allow-Origin', '*'
    res.json stgrSays: 'serving test!'

  lastChange: (req, res) ->
    console.log '\nOMG, a request!'
    console.info 'request made for:\n' + req.url

