 util  = require 'util'
 aws   = require 'aws2js'
 
-# sets up hooks to persist the brain into redis.
 module.exports = (robot) ->
 
   loaded            = false
   key               = process.env.HUBOT_S3_BRAIN_ACCESS_KEY_ID
   secret            = process.env.HUBOT_S3_BRAIN_SECRET_ACCESS_KEY
   bucket            = process.env.HUBOT_S3_BRAIN_BUCKET
+  # default to 30 minutes (in seconds)
+  save_interval     = process.env.HUBOT_S3_BRAIN_SAVE_INTERVAL || 30 * 60
   brain_dump_path   = "#{bucket}/brain-dump.json"
 
   if !key && !secret && !bucket
     throw new Error('S3 brain requires HUBOT_S3_BRAIN_ACCESS_KEY_ID, ' +
       'HUBOT_S3_BRAIN_SECRET_ACCESS_KEY and HUBOT_S3_BRAIN_BUCKET configured')
+
+  save_interval = parseInt(save_interval)
+  if isNaN(save_interval)
+    throw new Error('HUBOT_S3_BRAIN_SAVE_INTERVAL must be an integer')
 
   s3 = aws.load('s3', key, secret)
 

  store_current_brain = () ->
    store_brain robot.brain.data

  # 30 minute timer based save to limit s3 PUT requests
  time = 30 * 60 * 1000
  intervalId = setInterval store_current_brain, time

  s3.get brain_dump_path, 'buffer', (err, response) ->
    # unfortunately S3 gives us a 403 if we have access denied OR
    # the file is simply missing, so no way of knowing if IAM policy is bad


  robot.brain.on 'loaded', () ->
    loaded = true
    robot.brain.resetSaveInterval(save_interval)
    store_current_brain()

  robot.brain.on 'save', () ->
    store_current_brain()

  robot.brain.on 'close', ->
    store_current_brain()
