#! /usr/bin/ruby -w
#
# Copyright (C) 2005  Yoshinori K. Okuji <okuji@enbug.org>
#
# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cvsdigest; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA



require 'getoptlong'

PROGNAME = 'cvsdigest_save'

def usage(status = 0)
  print <<EOS
Usage: #{PROGNAME} [OPTION...] %{sVv}
Save log information in Maildir-like format.

  -h, --help           print this message and exit
  -d, --directory=DIR  use the directory DIR instead of "/var/lib/loginfo"
  -p, --project=NAME   use the project NAME instead of "default"

Report bugs to <okuji@enbug.org>.
EOS
  exit(status)
end

def parse()
  opts = GetoptLong.new(
    [ "--help",      "-h",    GetoptLong::NO_ARGUMENT ],
    [ "--directory", "-d",    GetoptLong::REQUIRED_ARGUMENT ],
    [ "--project",   "-p",    GetoptLong::REQUIRED_ARGUMENT ]
  )
  opts.quiet = true

  project = 'default'
  directory = '/var/lib/cvsdigest'

  begin
    opts.each do |opt, arg|
      case opt
      when '--help'
        usage(0)
      when '--project'
        project = arg
      when '--directory'
        directory = arg
      end
    end
  rescue
    STDERR.puts('#{PROGNAME}: ' + opts.error_message)
    STDERR.puts('Try `#{PROGNAME} --help` for more information.')
    exit 1
  end

  if ARGV.size == 0
    STDERR.puts('#{PROGNAME}: no argument specified')
    STDERR.puts('Try `#{PROGNAME} --help` for more information.')
    exit 1
  elsif ARGV.size > 1
    STDERR.puts('#{PROGNAME}: too many arguments specified')
    STDERR.puts('Try `#{PROGNAME} --help` for more information.')
    exit 1
  end

  yield directory, project, ARGV[0]
end

def unique_file(directory, project, user)
  time = Time.new.strftime('%Y%m%d%H%M%S')
  pid = Process.pid
  filename = time + user.gsub(/\//, '_') + Process.pid.to_s
  path = File.join(directory, project, 'tmp', filename)
  File.open(path, 'w') do |file|
    yield file
  end
  new_path = File.join(directory, project, 'new', filename)
  File.rename(path, new_path)
end

parse() do |directory, project, tokens|
  user = (ENV['CVS_USER'] or ENV['USER'])
  unique_file(directory, project, user) do |file|
    file << user << "\n"
    file << Time.new.strftime('%Y-%m-%d %H:%M:%S') << "\n"
    file << tokens << "\n"
    file << STDIN.read
  end
end
