#!/usr/bin/ruby

=begin

This is an example usage of 'ftp_sync'. 
Usually, you start editing files on Windows boxes by double-cliciking them.
Run this script, and the files will be synchronized with the master file
on a remote FTP server *before* and *after* invoking the default editor.

The default editor for the given application is read from the registry.

Usage:

    sync_citydesk.rb   "C:\My Files\my_proj.cty"

=end


def require_local file

    wdir= Dir.getwd
    Dir.chdir File.dirname(__FILE__)
    require File.join('.',file)
    Dir.chdir wdir
end


require 'win32/registry'
require_local 'ftp_sync'


def File.extension(filename)
    m = filename.match(/.*(\.[^\.]+)\Z/)
    return m[1]
end



def main(filename)

    raise "Filename not specified" if filename.nil? or filename.empty?

    ext = File.extension( filename )
    
    cmd = get_hadler_command(ext)
    
    if cmd.include? '%1'
        cmd.sub!('%1',filename)
    else
        cmd += " \"#{filename}\""
    end
    
    
    # This is the important stuff:
    # Synchronize the file before and after running an editing application
    # which potentially modifies the file.
    
    ftp_sync filename
    
    system cmd
    
    ftp_sync filename
    
    
end





def get_hadler_command(extension)
    hkcr = Win32::Registry::HKEY_CLASSES_ROOT
    hkcr.open(extension) do |reg|
        handler_type = reg['']
        hkcr.open( handler_type + '\shell\open\command') do |key|
            return key['']
        end
    end
end



if __FILE__ == $0
    begin
    
        main ARGV[0]
    
    rescue Exception => e 
        message "Encountered exception"
        message e.to_s
        pause
        raise
    end
end


