#!/usr/bin/env ruby
#
# $Id: ct2z,v 1.21 2004/12/07 11:04:22 ianmacd Exp $
#
# Program to convert the coming 12 months of CorporateTime calendar events to
# Sharp Zaurus calendar format.
#
# Copyright (C) 2002-2004 Ian Macdonald
#
#   This program 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, or (at your option)
#   any later version.
#
#   This program 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 this program; if not, write to the Free Software Foundation,
#   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

begin
  require 'password'
rescue LoadError
  $stderr.puts "This program requires Ruby/Password: http://www.caliban.org/ruby/"
  exit 1
end

begin
  require 'rexml/document'
rescue LoadError
  $stderr.puts "This program requires REXML: http://www.germane-software.com/software/rexml/"
  exit 1
end

require 'ctime'
require 'date'

include REXML

server = nil; line_nr = __LINE__
user = nil
passwd = nil

dot_mycal = ENV['HOME'] + '/.mycal'

if File.stat(dot_mycal).mode & 2 == 2
  $stderr.printf("%s is world-writable. Please fix this.\n", dot_mycal)
  exit 1
end

if FileTest.readable?(dot_mycal)
  File.open(dot_mycal) do |file|
    while line = file.gets
      eval line
    end
  end
end


if server.nil?
  $stderr.puts "Please define a CorporateTime server in either line " +
	       "#{line_nr} of this program or in a ~/.mycal file."
  exit 1
end

user ||= ( print "Username: "; gets.chomp )
passwd ||= Password.getc("Calendar password: ")

start_date = DateTime.now
end_date = start_date + 365

ct = CTime.new.connect(server, user, passwd)

a = ct.open_agenda(user)
events = a.get_events(start_date, end_date)
a.close
ct.quit

xml = XMLDecl.new
xml.xmldecl('1.0', 'UTF-8', nil)
doc = Document.new('<!DOCTYPE DATEBOOK>')
doc << xml

parent = doc.add_element('DATEBOOK')
ridmax = parent.add_element('RIDMax')
parent = parent.add_element('events')

rid = 0
events.sort {|a,b| a.start_time <=> b.start_time}.each do |e|

  # N.B. all-day events are not handled
  start_time = e.start_time
  end_time = e.end_time

  event = parent.add_element('event')
  event.add_attribute('description', e.summary)
  event.add_attribute('location', e.location)
  event.add_attribute('uid', (-start_time.tv_sec).to_s)
  event.add_attribute('rid', (rid += 1).to_s)
  event.add_attribute('rinfo', '1')
  event.add_attribute('alarm', '5')
  event.add_attribute('sound', 'loud')
  event.add_attribute('start', start_time.to_s)
  event.add_attribute('end', end_time.to_s)
  event.add_attribute('note', e.description)

end

ridmax.add_text(rid.to_s)

doc.write($stdout, 0)
