require 'docusign_rest'

namespace :docusign_rest do

desc "Retrive account_id from the API"
task :generate_config do
  def ask(message)
    STDOUT.print message
    STDIN.gets.chomp
  end

  STDOUT.puts %Q{

Please do the following:


1) Login or register for an account at demo.docusign.net

...or their production url if applicable

2) From the Avatar menu in the upper right hand corner of the page, click “Go to Admin” 3) From the left sidebar menu, click “API and Keys” 4) Request a new 'Integrator Key' via the web interface

 * You will use this key in one of the next steps to retrieve your 'accountId'\n\n}

username = ask('Please enter your DocuSign username: ')
password = ask('Please enter your DocuSign password: ')
integrator_key = ask('Please enter your DocuSign integrator key: ')

DocusignRest.configure do |config|
  config.username       = username
  config.password       = password
  config.integrator_key = integrator_key
end

# initialize a client and request the accountId
client = DocusignRest::Client.new
acct_id = client.get_account_id

puts ""

# construct the configure block for the user with his or her credentials and accountId
config = %Q{# This file was generated by the docusign_rest:generate_config rake task.

# You can run 'rake docusign_rest:generate_config' as many times as you need # to replace the content of this file with a new config.

require 'docusign_rest'

DocusignRest.configure do |config|

config.username       = '#{username}'
config.password       = '#{password}'
config.integrator_key = '#{integrator_key}'
config.account_id     = '#{acct_id}'
#config.endpoint       = 'https://www.docusign.net/restapi'
#config.api_version    = 'v2'

endnn}

# write the initializer for the user
if defined?(Rails)
  docusign_initializer_path = Rails.root.join("config/initializers/docusign_rest.rb")
else
  docusign_initializer_path = "test/docusign_login_config.rb"
end

File.open(docusign_initializer_path, 'w') { |f| f.write(config) }
# read the initializer file into a var for comparison to the config block above
docusign_initializer_content = File.open(docusign_initializer_path) { |io| io.read }

# if they match tell the user we wrote the file, otherwise tell them to do it themselves
if docusign_initializer_content.include?(config)
  if defined?(Rails)
    puts "The following block of code was added to config/initializers/docusign_rest.rb\n\n"
  else
    puts "The following block of code was added to test/docusign_login_config.rb\n\n"
  end
  puts config
else
  puts %Q{The config file was not able to be automatically created for you.

Please create it at config/initializers/docusign_rest.rb and add the following content:nn}

    puts config
  end
end

end