#! /usr/bin/env ruby
require File.dirname(__FILE__) + '/lib/base'
require File.dirname(__FILE__) + '/lib/csv'

class PasswordSafe3Importer < Importer
  
  def process_contents(contents)
    contents = contents.gsub("\r", "\n")
    reader = CSV::Reader.create(contents, "\t", nil)
    while true
      row = []
      parsed_cells = reader.get_row(row) rescue nil
      break if parsed_cells == 0

#      Group/Title	Username	Password	URL	AutoType	Created Time	Password Modified Time	Last Access Time	Password Expiry Date	Record Modified Time	History	Notes
      next if row.nil? || row.size < 10
      next if row[0] == "Group/Title"

      folderPath = ""
      title = row.shift
      if title =~ /(.*)\.(.+)/
        folderPath = $1
        title = $2
      end
      
      username = row.shift
      password = row.shift
      url = row.shift
      
      row.shift # AutoType
      row.shift # created time
      row.shift # password modified time
      row.shift # last access time
      row.shift # expiry date
      row.shift # record modified type
      row.shift # history

      notes = row.shift || ""
      notes.gsub!(/»/, "\n")
      
      item = WebForm.new
      item.title = title
      item.folderPath = folderPath
      item.location = url
      item.add_login(username, password)
      item.notes = notes
      
      add_item(item)
    end
  end
  
end

PasswordSafe3Importer.new.run
