#!/usr/bin/ruby1.6 -Ke
# -*- ruby -*-

### mhc2palm -- copy articles from mhc to palm.
##
## Author:  Yoshinari Nomura <nom@quickhack.net>
##
## Created: 1999/10/08
## Revised: 2001/09/13 05:15:17
##

$DEBUG = false

STDOUT .sync= true
STDERR .sync= true

require 'mhc-kconv'
require 'mhc-palm'
require 'mhc-date'
require 'mhc-schedule'

def usage
  print '
usage: mhc2palm [-a | -i] [-n] [-d dev] [-r dir] [YYYYMMDD-yyyymmdd]

  mhc2palm -- Add/Copy mhc articles to a palm.

    -v     : Verbose mode.
    -a     : Add mhc articles to a palm.
             all the original records of the palm will remain.
    -i     : Copy mhc articles into the palm.
             all the original records of palm will be lost.
    -n     : Do nothing effectives. Useful for checking.
    -d dev : Set the device file connected to the palm.
             default value is /dev/pilot
    -r dir : Set repository directory of the mhc.
             ~/Mail/schedule

    YYYYMMDD-yyyymmdd : set a start and end date of scanning mhc.
                        if omitted, scan from 3 months ago to
                        3 months after.
'
  exit 1
end

##
## sub routines.
##

def send_to_palm(pdb, p_rec_array)
  new_id_array = []
  p_rec_array .each{|p_rec|
    if new_id = pdb .write_record(p_rec)
      print "(new_id = #{new_id}) " if $flag_verbose
      new_id_array << new_id
    else
      return nil # fail.
    end
  }
  print "\n"  if $flag_verbose
  return new_id_array # success.
end


##
## option check.
##

$flag_verbose = false
$flag_noharm, $flag_append, $flag_install = false, false, false
$flag_device, $flag_from, $flag_to = '/dev/pilot', nil, nil
$flag_dir = File .expand_path("~/Mail/schedule")

while ARGV .length > 0
  case ARGV[0]
  when '-v'
    $flag_verbose = true
  when '-a'
    $flag_append  = true
  when '-i'
    $flag_install = true
  when '-n'
    $flag_noharm  = true
  when '-d'
    ARGV .shift
    $flag_device  = ARGV[0]
  when '-r'
    ARGV .shift
    $flag_dir = ARGV[0]
  when /^(\d{8})-(\d{8})$/
    $flag_from, $flag_to = MhcDate .new($1), MhcDate .new($2)
  else
    usage()
  end
  ARGV .shift
end

$flag_from = MhcDate .new .m_succ!(-3) if !$flag_from
$flag_to   = MhcDate .new .m_succ!(+3) if !$flag_to

usage() if !($flag_append || $flag_install) || ($flag_append && $flag_install)

##
## Initialize & open palm
##

if !$flag_noharm
  if !File .exist?($flag_device)
    STDERR .print "Can not open #{$flag_device}.\n"
    exit 1
  end
  psock = Pilot .new($flag_device)
  STDERR .print "Press Sync Button\n"
  psock .listen
  pdb = PilotApptDB .new(psock, "DatebookDB")
end

if $flag_install
  print "delete all articles in the palm."

  if !$flag_noharm
    print (pdb .delete_all ? ".. succeed." : ".. failed.")
  end
  print "\n"
end

##
## Open mhc & copy to palm
##

sch_count, sent = 0, 0

mdb = MhcScheduleDB .new($flag_dir)
mdb .each_sch($flag_from, $flag_to){
  sch_count += 1
}
mdb .each_sch($flag_from, $flag_to){|sch|

  print "adding ", MhcKconv::todisp(sch .subject), "\n" if $flag_verbose

  if p_rec_array = sch .to_palm
    if $flag_verbose
      print "    converted into #{p_rec_array .length} palm article#{p_rec_array .length == 1 ? '' : 's'}."
    end

    if !$flag_noharm
      print " sending to palm ...\n    " if $flag_verbose
      if (! (send_to_palm(pdb, p_rec_array) .nil?))
	sent += 1
	print "#{sent}/#{sch_count}\r"
      else
	print MhcKconv::todisp("\n(#{sch .subject}) write_error\n")
      end
    else
      print " not sent.\n" if $flag_verbose
    end
  else
    print "failed to convert."
    print MhcKconv::todisp("  subject: #{sch .subject}\n")
    print "  first occured: #{sch .occur_min}\n"
    print "  path: #{sch .path}\n"
  end
  print "\n"  if $flag_verbose
}
print "#{sent}/#{sch_count} article#{sent == 1 ? '' : 's'} successfully sent.\n"

##
## close palm & exit
##

if !$flag_noharm
  pdb .reset_sync_flags  ## remove all dirty flag in palm.
  pdb .close
  psock .close
end
exit 0

### Copyright Notice:

## Copyright (C) 1999, 2000 Yoshinari Nomura. All rights reserved.
## Copyright (C) 2000 MHC developing team. All rights reserved.

## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## 
## 1. Redistributions of source code must retain the above copyright
##    notice, this list of conditions and the following disclaimer.
## 2. Redistributions in binary form must reproduce the above copyright
##    notice, this list of conditions and the following disclaimer in the
##    documentation and/or other materials provided with the distribution.
## 3. Neither the name of the team nor the names of its contributors
##    may be used to endorse or promote products derived from this software
##    without specific prior written permission.
## 
## THIS SOFTWARE IS PROVIDED BY THE TEAM AND CONTRIBUTORS ``AS IS''
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
## FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
## THE TEAM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
## INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
## HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
## STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
## OF THE POSSIBILITY OF SUCH DAMAGE.

### mhc2palm ends here
