#!/usr/local/bin/ruby -w

# Norbert Wigbels
#
#######################################################################
# A little script that copies imagefiles from your
# Sony Ericsson K700i mobilephone to <destination>
#######################################################################
#
# 

def usage
    puts "usage: m2a.rb <destination>"
    exit(-1)
end

usage if ARGV.length != 1
$destination  = ARGV[0]

# SE K700i organizes the camera pictures in Bilder/camera_semc
BD_ADDR   = "trebroN"
OBEX_DIR1 = "Bilder"
OBEX_DIR2 = "camera_semc"


def doCrudeObexAppComm
    begin
        cam = getObexIOObject
        cam.puts "ls"
        cam.close_write
        lines = cam.readlines
        cam = getObexIOObject
        lines.each do |line|
            line =~ /Bild\(\d+\).jpg/
            #black-magic-ruby $& holds the match
            if !$&.nil?
                cam.puts "get"
                cam.puts $&
                cam.puts $destination+'/'+$&
                puts "copy picture "+$&+" to to "+$destination
                #delete picturea after copying? uncomment...
                #doesn't work on my phone:(
                #cam.puts "delete"
                #cam.puts $&
            end
    end
    rescue Exception => ex
        puts(ex.to_s)
    ensure
        # TODO: ensure connection is closed
        cam.puts "disconnect" 
        cam.close
    end
end

def getObexIOObject
        cam = IO.popen("obexapp -a #{BD_ADDR} -C OPUSH",  "w+")
        cam.puts "cd #{OBEX_DIR1}"
        cam.puts "cd #{OBEX_DIR2}"
        return cam
end

# start here
doCrudeObexAppComm

