#!/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-property [OPTIONS] RANGES

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_force = false
opt_quiet = false
opts = OptionParser.new do |opts|
  opts.banner = <<"End"
Usage: #{$0} [OPTIONS] PROPS RANGES
where PROPS is a comma seperated list of properties to be up to date.
RANGES is a comma separated list of global numbers assigned by import
command.  If it is -, #{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('--force', '-f', 'Overwrite existing properties.') do
    opt_force = true
  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

if ARGV.length < 1
  $stderr.print(opts.to_s)
  exit(1)
end
  
begin
  require 'msgcab/cli/property'

  cli = MsgCab::CLI::Property.new({:quiet => opt_quiet, :force => opt_force})

  props = ARGV.shift.split(/\s*,\s*/)
  props.uniq!
  if ARGV.empty?
    numbers = Array.new
  else
    ranges = ARGV.shift
    ranges = $stdin.read if ranges == '-'
    numbers = MsgCab::CLI.uncompress_numbers(ranges)
  end
  cli.update(props, numbers)
rescue Exception => e
  $stderr.puts("Error: #{e}\n#{e.backtrace.join("\n")}")
  exit(1)
ensure
  MsgCab::CLI.database.disconnect
end
