#!/usr/bin/env ruby
#
# $Id: find_slot,v 1.5 2003/11/13 11:13:40 ianmacd Exp $
#
# simple program to find the first free slot on a given agenda
#
# Copyright (C) 2002 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

require 'ctime'
require 'date'
require 'getoptlong'

def usage(code = 0)
  prog_name = File::basename($0)
  $stderr.print "
Usage: #{prog_name} [-d|--duration <duration>] <agenda>
       #{prog_name} -h|--help

-d, --duration    find a slot for at least this number of minutes (default: 60)
-h, --help        show this usage message
"
  exit code
end

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

duration = 60

dot_mycal = ENV['HOME'] + '/.mycal'
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

opt = GetoptLong.new(
  ['--duration',	'-d', GetoptLong::REQUIRED_ARGUMENT],
  ['--help',		'-h', GetoptLong::NO_ARGUMENT])

begin
  opt.each_option do |name,arg|
    case name
    when '--duration'
      duration = arg.to_i
    when '--help'
      usage
    end
  end
rescue
  usage 1
end

agenda = ARGV[0]
usage 1 if agenda.nil?

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

now = Time.now.gmtime
today = Date.today
finish = today + 60

start_date = sprintf("%s%02d%02dT%02d%02d00Z",
		     today.year, today.month, today.day, now.hour, now.min)
end_date = sprintf("%s%02d%02dT%02d%02d00Z",
		   finish.year, finish.month, finish.day, now.hour, now.min)

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

unless ct.error == "CAPI_STAT_OK"
  printf("Failed to connect to %s as user %s\n", server, user)
  exit 2
end

ct.open_agenda(agenda)
puts "Fetching agenda..."
events = ct.get_events(start_date, end_date)

end_time = now
events.sort {|a,b| a.start <=> b.start}.each do |e|

  year, month, day, hours, mins, secs =
    /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.match(e.start)[1..6]
  start_time = Time.gm(year, month, day, hours, mins, secs)

  if (end_time + duration * 60) <= start_time &&
     end_time.localtime.wday != 0 && end_time.localtime.wday != 6

    printf("The next available %d minute slot is on\n%s", duration,
    end_time.localtime.strftime("%A, %B %d, %Y at %H:%M"))

    print "\nBook it, keep looking or quit? (b/l/q) "
    response = $stdin.gets.chomp

    exit if response =~ /^q/i

    if response !~ /^b/i
      end_time += duration * 60
      puts
      redo
    end

    end_time.gmtime
    massage = Event.new(sprintf("%s%02d%02dT%02d%02d00Z", end_time.year,
				end_time.month, end_time.day,
				end_time.hour, end_time.min),
			sprintf("P0DT%02dH%02dM00S", duration / 60,
				duration % 60),
			"Massage for " + user)

    ct.open_agenda(user)
    if ct.set_event(massage)
      puts "Booked!"
      ct.quit

      exit 0
    else
      puts "Booking failed!"
      ct.quit

      exit 1
    end

  end

  if ! e.duration.nil?  # CAPI 2.0
    d_hours, d_mins, d_secs =
      /^P\dDT(\d+)H(\d+)M(\d+)S$/.match(e.duration)[1..3]
    new_end_time = start_time + d_hours.to_s.to_i * 3600 + d_mins.to_s.to_i *
		   60 + d_secs.to_s.to_i
  else			# CAPI 2.5 or later
    e_year, e_month, e_day, e_hours, e_mins, e_secs =
      /^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)Z$/.match(e.end)[1..6]
    new_end_time = Time.gm(e_year, e_month, e_day, e_hours, e_mins, e_secs)
  end

  if new_end_time > end_time
    end_time = new_end_time
  end

end

printf("I didn't look any further than %s\n",
       end_time.localtime.strftime("%A, %B %d, %Y"))

ct.quit
