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

# Format:

# *** Group: Group1 ***
# 
# *** Group: Group2 ***
# 
#   Title:    title
#   Username: user
#   Url:      1passwd.com
#   Password: password
#   Comment:  nice comments
# 
#   Title:    item2
#   Username: user
#   Url:      aws.com
#   Password: a
#   Comment:  a comment.

class KeePassXImporter < 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

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

      if line =~ /^\s*Username:\s*(.*)/
        @username = $1 
        next
      end
      
      if line =~ /^\s*Url:\s*(.*)/
        @url = $1 
        next
      end
      
      if line =~ /Password:\s*(.*)/
        @password = $1 
        next
      end
      
      if line =~ /Comment:\s*(.*)/
        @comment = $1 
        next
      end
      
      if @title
        # Either a continuation of a comment or syntax error
        if line =~ /   (.*)/
          @comment = "#{@comment}\n#{$1.strip}"
        end
      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

KeePassXImporter.new.run
