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

# Format:

# [Apple ID Mardi]
#
# Group: IT
#
# User Name: nnn
#
# URL: 
#
# Password: xxxx
# 
# Notes:
#
# [ARNnet]
#
# Group: IT
# 
# User Name: mg
#
# URL: www.arnnet.com.au
# 
# Password: xxxx
# 
# Notes: subcribe with ieee add
# 
# clue is mothers maiden name


class KeePassImporter < Importer
  
  attr_accessor :title, :username, :url, :password, :comment, :curent_group
  
  def process(lines)
    
    @current_group, @title, @username, @url, @password, @comment = nil,nil,nil,nil,nil,nil
    
    for line in lines do

      next if line.strip == ""

      if line =~ /^\[(.*)\]$/
        create_web_form if @title
        @title = $1
        next
      end
      
      if line =~ /^\s*Group:\s*(.*)/
        @current_group = $1
        next
      end

      if line =~ /^\s*User Name:\s*(.*)/
        @username = $1 
        next
      end
      
      if line =~ /^\s*URL:\s*(.*)/
        @url = $1 
        next
      end
      
      if line =~ /Password:\s*(.*)/
        @password = $1 
        next
      end
      
      if line =~ /Notes:\s*(.*)/
        @comment = $1 
        next
      end
      
      if @title
        # Either a continuation of a comment or syntax error
        @comment = "#{@comment}\n#{line.strip}"
      end
      
    end
    
    unless @title.nil?
      create_web_form
    end
  end
  
  def create_web_form
    f = WebForm.new
    f.name = "#{@current_group}\\#{@title}"
    f.url = @url
    f.add_login(@username, @password)
    f.notes = @comment
    add_item f
    @title, @username, @url, @password, @comment = nil,nil,nil,nil,nil
  end
  
end

KeePassImporter.new.run
