#!/usr/bin/env ruby

ENV["RAILS_ENV"] ||= "production"

APP_PATH = File.expand_path("../../config/application", __FILE__)
require File.expand_path("../../config/boot", __FILE__)
require APP_PATH
Rails.application.require_environment!

# postfix exit codes
EX_NOUSER = 67
EX_TEMPFAIL = 75
EX_UNAVAILABLE = 69

message = ""
until $stdin.eof?
  message += $stdin.gets.to_s
end

parser = EmailParser.new(ARGV[1], ARGV[0], message)

if parser.been_here?
  # avoid looping, quietly
  exit

elsif !parser.sending_user
  warn "no active user with mailing list token #{parser.user_token}"

  # if this looks like a user token but invalid, generate a bounce to be
  # helpful.  otherwise supress it to avoid talking back to spammers
  exit(parser.user_token ? EX_NOUSER : 0)

elsif !parser.email
  warn "error parsing e-mail"
  exit EX_UNAVAILABLE

elsif !parser.parent
  warn "no valid comment or story being replied to"
  exit EX_NOUSER

elsif parser.body.blank?
  warn "no valid text/plain body found"
  exit EX_UNAVAILABLE
end

c = Comment.new
c.user_id = parser.sending_user.id
c.comment = parser.body
c.is_from_email = true

if parser.parent.is_a?(Comment)
  c.story_id = parser.parent.story_id
  c.parent_comment_id = parser.parent.id
else
  c.story_id = parser.parent.id
end

if c.save
  exit
else
  warn c.errors.inspect
  exit EX_UNAVAILABLE
end
