#! /usr/bin/env rails runner
# -*- mode: Ruby;-*-
#
# Run this with script/runner
#
# TODO: use Thor when we migrate to Rails 3

require 'yaml'



# TODO: update the /etc/hosts directly
def domains(hosts = nil)
  hosts = Account.providers.map do |a|
    "#{a.domain}.dev #{a.self_domain}.dev"
  end.join(' ')

  hosts = "127.0.0.1 #{hosts}"
  puts hosts

  begin
    IO.popen('xclip -i','w') { |io| io.puts(hosts) }
    puts 'Hosts record saved to clipboard.'
  rescue
  end
end


def unlock
  ensure_development

  delete_site_key(Account.master)
  Account.providers.update_all("site_access_code = NULL")
  puts "Access codes deleted."

  User.update_all "crypted_password='c944509aabc533481b629624f1b8c3fcab3fb189', salt='b6cf550fa43984acafe24dfecd40b5d37818aa57'"
  puts "All users' passwords set to 'p'."

  Cinstance.joins(:user_account).where("accounts.provider = true").update_all("cinstances.user_key = 'p'")
  puts "All provider keys set to 'p'."
end


def mangle
  ensure_development

  Account.update_all 'credit_card_authorize_net_payment_profile_token = NULL, credit_card_auth_code = NULL, payment_gateway_options = NULL'
end


def delete_site_key(a)
  a.update_attribute(:site_access_code, nil)
  puts "'#{a.org_name}' has no access code and domain #{a.domain}"
end


def list(what)
  if what == 'users'
    puts User.all.map(&:username).join("\n")
  else
    puts 'Only users supported yet.'
  end
end


def browse(org_name)
  domain = if org_name == 'master'
             Account.master.domain
           else
             Account.find_by_org_name(org_name)
           end

  exec "google-chrome #{domain2local(domain)}"
end


def run_server(mode)

  case mode.to_sym
    when :connect then change_db_to '3scale_system_development_remonster'
    when :enterprise then change_db_to '3scale_system_enterprise'
    else puts 'I must give a correct mode'
  end
  exec "script/server"
end


def change_db_to(db)
  puts 'Change data base to ' + db
  database = 'config/database.yml'
  settings = YAML::load_file(database)
  settings["development"]["database"] = db

  File.open(database, 'w') do |f|
    YAML.dump(settings, f)
  end
end

def ensure_development
  unless Rails.env.development?
    puts 'You can run this only in development.'
    exit
  end
end


def help
  puts '''
     domains                             - print all available local domains
     mangle                              - remove sensitive data
     unlock                              - delete site access keys, set passwords and provider keys "p",
     browse [org_name]                   - opens browser on login page for that account
     list users                          - list all usernames
     run_server [connect | enterprise]   - run server in correct mode
  '''
end


if ARGV.empty?
  help
else
  begin
    send(ARGV.shift, *ARGV)
  rescue NoMethodError
    help
  end
end
