 
   db.get "SELECT COUNT(*) FROM metadata", (err, row) ->
     if err
-      db.run "CREATE TABLE metadata (key TEXT, value TEXT)", (err) ->
-        if err then return cb "Couldn't create metadata table for team #{team}"
-        db.run "INSERT INTO metadata VALUES($key, $value)", {$key: key, $value: value}, (err) ->
-          if err then return cb "Couldn't insert metadata #{key} into table for team #{team}: #{err}"
-          log.info "Set metadata key #{key} for team #{team} with new table"
-          return cb null
+      async.series [
+        (cb) -> db.run "CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT)", cb
+        (cb) -> db.run "CREATE TABLE factoids (key TEXT PRIMARY KEY, value TEXT, last_edit TEXT)", cb
+        (cb) -> db.run "INSERT INTO metadata VALUES($key, $value)", {$key: key, $value: value}, cb
+      ], (err) ->
+        if err then return cb "Couldn't initialize metadata for team #{team}: #{err}"
+        log.info "Set metadata key #{key} for team #{team} with new table"
+        return cb null
     else
-      db.run "UPDATE metadata SET value = $value WHERE key = $key", {$key: key, $value: value}, (err) ->
+      db.run "INSERT OR REPLACE INTO metadata VALUES($key, $value)", {$key: key, $value: value}, (err) ->
         if err then return cb "Couldn't update metadata for team #{team}: #{err}"
         log.info "Set metadata key #{key} for team #{team} with existing table"
         return cb null
+
+# BOTS --------------------------------------------------------------------------
+
+bots = {}
+
+controller = Botkit.slackbot(
+  clientID: process.env.SLACK_CLIENT_ID
+  clientSecret: process.env.SLACK_CLIENT_SECRET
+  scopes: ['bot']
+  debug: process.env.DEBUG
+  send_via_rtm: true
+)
+
+#handler = (event) ->
+  #return (bot, msg) ->
+    #return if msg.type in ['user_typing', 'desktop_notification']
+    #return if msg.user is bot.identity?.id
+    #console.log new Array(80).join('-')
+    #console.log "TEAM: #{bot.identifyTeam()} - TYPE: #{event} - DATA:"
+    #console.log inspect msg
+    #bot.reply msg, text: "#{event} ```#{inspect msg}```", (err) ->
+      #log.error "Failed to reply: #{err}"
+#for i in ['message_received', 'mention', 'direct_message', 'direct_mention', 'ambient']
+  #controller.on i, handler(i)
+
+handleMessage = (bot, channel, isDirect, message) ->
+  team = bot.identifyTeam()
+  bot.reply {
+    channel: channel
+  }, {
+    text: ":star: channel=#{channel} isDirect=#{isDirect} message=#{message}"
+  }
+
+controller.on 'direct_mention', (bot, msg) ->
+  return if msg.user is bot.identity?.id
+  handleMessage bot, msg.channel, true, msg.text
+
+controller.on 'direct_message', (bot, msg) ->
+  return if msg.user is bot.identity?.id
+  handleMessage bot, msg.channel, true, msg.text
+
+controller.on 'ambient', (bot, msg) ->
+  return if msg.user is bot.identity?.id
+  name = bot.identity?.name
+  text = msg.text
+  if text.toLowerCase().indexOf("#{ name } ") == 0
+    text = text.substr(name.length + 1)
+    handleMessage bot, msg.channel, true, text
+  else
+    handleMessage bot, msg.channel, false, text
+  return
+
+startBot = (team) ->
+  log.info "Starting bot for team #{team}..."
+
+  if team of bots
+    log.warning "Bot for #{team} already started. Returning."
+    return
+
+  getMetaData team, 'token', (err, token) ->
+    if err
+      log.error "Couldn't get token for #{team}: #{err}"
+      return
+    bot = bots[team] = controller.spawn(token: token)
+    bot.startRTM()
+
+for file in fs.readdirSync process.env.DATA_DIR
+  log.info "Found db file for #{file}"
+  startBot(file)
+
+# LOGIC -------------------------------------------------------------------------
+


  db.get "SELECT value FROM metadata WHERE key = $key", {$key: key}, (err, row) ->
    if err then return cb "Couldn't get metadata for team #{team}: #{err}"
    return cb null, row[0]

setMetaData = (team, key, value, cb) ->
  db = getDatabase team


require('dotenv').config()

Botkit = require 'botkit'
SlackStrategy = require('./lib/passport-slack.js')
async = require 'artillery-async'
bodyParser = require 'body-parser'
