#!/usr/bin/env ruby

# Copyright (C) 2004, 2005  National Institute of Advanced Industrial Science and Technology
#
# This file is part of msgcab.
#
# msgcab 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.
#
# msgcab 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 msgcab; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Usage:
#   ./msgcab-import [OPTIONS] SOURCE...
#   ./msgcab-import [OPTIONS]

require 'pathname'
require 'optparse'

path = Pathname.new($0).realpath.dirname
$LOAD_PATH.unshift((path + 'lib').to_s)
$KCODE = 'UTF8'

require 'msgcab/config'

MsgCab::FLAVOR = 'cli'
MsgCab::Config.load(path + 'config.yml')

opt_quiet = false
opt_props = ['filter', 'title']
opts = OptionParser.new do |opts|
  opts.banner = <<"End"
Usage: #{$0} [OPTIONS] SOURCE...
Usage: #{$0} [OPTIONS]
where SOURCE is either a file which contains at most one message, or a
Maildir directory.  If it is omitted, #{File.basename($0)} reads a
message from standard input.
End
  opts.on('--quiet', '-q', 'Suppress all normal output.') do
    opt_quiet = true
  end
  opts.on('--properties=PROPS', '-p', 'Update PROPS properties.') do |props|
    opt_props |= props.split(/\s*,\s*/)
  end
  opts.on_tail('--help', '-h', 'Show this message.') do
    $stdout.print(opts.to_s)
    exit(0)
  end
end

begin
  opts.parse!(ARGV)
rescue OptionParser::ParseError
  $stderr.print(opts.to_s)
  exit(1)
end

require 'msgcab/source'
require 'msgcab/cli/register'
require 'msgcab/cli/property'

sources = Array.new
if ARGV.empty?
  sources << MsgCab::IOSource.new(ARGF)
else
  ARGV.each do |path|
    sources << MsgCab::Source.open(Pathname.new(path))
  end
end

begin
  sources.each do |source|
    $stderr.puts("#{File.expand_path(source.path)}:") unless opt_quiet
    register_cli = MsgCab::CLI::Register.new({:quiet => opt_quiet})
    numbers = register_cli.register(source)
    property_cli = MsgCab::CLI::Property.new({:quiet => opt_quiet})
    property_cli.update(opt_props, numbers)
    $stderr.puts("#{numbers.length} messages imported.") unless opt_quiet
  end
rescue Exception => e
  $stderr.puts("Error: #{e}\n#{e.backtrace.join("\n")}") unless opt_quiet
  exit(1)
ensure
  MsgCab::CLI.database.disconnect
end
