#!/usr/bin/env ruby

# Arvados cli client
#
# Ward Vandewege <ward@curoverse.com>

require 'fileutils'

if RUBY_VERSION < '1.9.3' then
  abort <<-EOS
#{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
  EOS
end

begin
  require 'curb'
  require 'rubygems'
  require 'arvados/google_api_client'
  require 'json'
  require 'pp'
  require 'trollop'
  require 'andand'
  require 'oj'
  require 'active_support/inflector'
  require 'yaml'
  require 'tempfile'
  require 'net/http'
rescue LoadError
  abort <<-EOS

Please install all required gems:

  gem install activesupport andand curb google-api-client json oj trollop yaml

  EOS
end

# Search for 'ENTRY POINT' to see where things get going

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'specimen', 'specimens'
  inflect.irregular 'human', 'humans'
end

module Kernel
  def suppress_warnings
    original_verbosity = $VERBOSE
    $VERBOSE = nil
    result = yield
    $VERBOSE = original_verbosity
    return result
  end
end

class ArvadosClient < Google::APIClient
  def execute(*args)
    if args.last.is_a? Hash
      args.last[:headers] ||= {}
      args.last[:headers]['Accept'] ||= 'application/json'
    end
    super(*args)
  end
end

def init_config
  # read authentication data from arvados configuration file if present
  lineno = 0
  config_file = File.expand_path('~/.config/arvados/settings.conf') rescue nil
  if not config_file.nil? and File.exist? config_file then
    File.open(config_file, 'r').each do |line|
      lineno = lineno + 1
      # skip comments
      if line.match('^\s*#') then
        next
      end
      var, val = line.chomp.split('=', 2)
      # allow environment settings to override config files.
      if var and val
        ENV[var] ||= val
      else
        warn "#{config_file}: #{lineno}: could not parse `#{line}'"
      end
    end
  end
end


subcommands = %w(copy create edit keep pipeline run tag ws)

def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
  case subcommand
  when 'create'
    arv_create client, arvados, global_opts, remaining_opts
  when 'edit'
    arv_edit client, arvados, global_opts, remaining_opts
  when 'copy', 'tag', 'ws', 'run'
    exec `which arv-#{subcommand}`.strip, *remaining_opts
  when 'keep'
    @sub = remaining_opts.shift
    if ['get', 'put', 'ls', 'normalize'].index @sub then
      # Native Arvados
      exec `which arv-#{@sub}`.strip, *remaining_opts
    elsif ['less', 'check'].index @sub then
      # wh* shims
      exec `which wh#{@sub}`.strip, *remaining_opts
    elsif @sub == 'docker'
      exec `which arv-keepdocker`.strip, *remaining_opts
    else
      puts "Usage: arv keep [method] [--parameters]\n"
      puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
      puts "Available methods: ls, get, put, less, check, docker"
    end
    abort
  when 'pipeline'
    sub = remaining_opts.shift
    if sub == 'run'
      exec `which arv-run-pipeline-instance`.strip, *remaining_opts
    else
      puts "Usage: arv pipeline [method] [--parameters]\n"
      puts "Use 'arv pipeline [method] --help' to get more information about specific methods.\n\n"
      puts "Available methods: run"
    end
    abort
  end
end

def command_exists?(command)
  File.executable?(command) || ENV['PATH'].split(':').any? {|folder| File.executable?(File.join(folder, command))}
end

def run_editor path
  pid = Process::fork
  if pid.nil?
    editor = nil
    [ENV["VISUAL"], ENV["EDITOR"], "nano", "vi"].each do |e|
      editor ||= e if e and command_exists? e
    end
    if editor.nil?
      abort "Could not find any editor to use, please set $VISUAL or $EDITOR to your desired editor."
    end
    exec editor, path
  else
    Process.wait pid
  end

  if $?.exitstatus != 0
    raise "Editor exited with status #{$?.exitstatus}"
  end
end

def edit_and_commit_object initial_obj, tmp_stem, global_opts, &block

  content = case global_opts[:format]
            when 'json'
              Oj.dump(initial_obj, :indent => 1)
            when 'yaml'
              initial_obj.to_yaml
            else
              abort "Unrecognized format #{global_opts[:format]}"
            end

  tmp_file = Tempfile.new([tmp_stem, ".#{global_opts[:format]}"])
  tmp_file.write(content)
  tmp_file.close

  begin
    error_text = ''
    while true
      begin
        run_editor tmp_file.path

        tmp_file.open
        newcontent = tmp_file.read()
        tmp_file.close

        # Strip lines starting with '#'
        newcontent = newcontent.lines.select {|l| !l.start_with? '#'}.join

        # Load the new object
        newobj = case global_opts[:format]
                 when 'json'
                   Oj.load(newcontent)
                 when 'yaml'
                   YAML.load(newcontent)
                 end

        yield newobj

        break
      rescue => e
        can_retry = true
        if e.is_a? Psych::SyntaxError
          this_error = "YAML error parsing your input: #{e}"
        elsif e.is_a? JSON::ParserError or e.is_a? Oj::ParseError
          this_error = "JSON error parsing your input: #{e}"
        elsif e.is_a? ArvadosAPIError
          this_error = "API responded with error #{e}"
        else
          this_error = "#{e.class}: #{e}"
          can_retry = false
        end
        puts this_error

        tmp_file.open
        newcontent = tmp_file.read()
        tmp_file.close

        if newcontent == error_text or not can_retry
          FileUtils::cp tmp_file.path, tmp_file.path + ".saved"
          puts "File is unchanged, edit aborted." if can_retry
          abort "Saved contents to " + tmp_file.path + ".saved"
        else
          tmp_file.open
          tmp_file.truncate 0
          error_text = this_error.to_s.lines.map {|l| '# ' + l}.join + "\n"
          error_text += "# Please fix the error and try again.\n"
          error_text += newcontent.lines.select {|l| !l.start_with? '#'}.join
          tmp_file.write error_text
          tmp_file.close
        end
      end
    end
  ensure
    tmp_file.close(true)
  end

  nil
end

class ArvadosAPIError < RuntimeError
end

def check_response result
  begin
    results = JSON.parse result.body
  rescue JSON::ParserError, Oj::ParseError => e
    raise "Failed to parse server response:\n" + e.to_s
  end

  if result.response.status != 200
    raise ArvadosAPIError.new("#{result.response.status}: #{
                              ((results['errors'] && results['errors'].join('\n')) ||
                                Net::HTTPResponse::CODE_TO_OBJ[status.to_s].to_s.sub(/^Net::HTTP/, '').titleize)}")
  end

  results
end

def arv_edit client, arvados, global_opts, remaining_opts
  uuid = remaining_opts.shift
  if uuid.nil? or uuid == "-h" or uuid == "--help"
    puts head_banner
    puts "Usage: arv edit [uuid] [fields...]\n\n"
    puts "Fetch the specified Arvados object, select the specified fields, \n"
    puts "open an interactive text editor on a text representation (json or\n"
    puts "yaml, use --format) and then update the object.  Will use 'nano'\n"
    puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
    exit 255
  end

  # determine controller

  m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match uuid
  if !m
    if /^[a-f0-9]{32}/.match uuid
      abort "Arvados collections are not editable."
    else
      abort "'#{uuid}' does not appear to be an Arvados uuid"
    end
  end

  rsc = nil
  arvados.discovery_document["resources"].each do |k,v|
    klass = k.singularize.camelize
    dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
    if dig == m[2]
      rsc = k
    end
  end

  if rsc.nil?
    abort "Could not determine resource type #{m[2]}"
  end

  begin
    result = client.execute(:api_method => eval('arvados.' + rsc + '.get'),
                            :parameters => {"uuid" => uuid},
                            :authenticated => false,
                            :headers => {
                              authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
                            })
    oldobj = check_response result
  rescue => e
    abort "Server error: #{e}"
  end

  if remaining_opts.length > 0
    oldobj.select! { |k, v| remaining_opts.include? k }
  end

  edit_and_commit_object oldobj, uuid, global_opts do |newobj|
    newobj.select! {|k| newobj[k] != oldobj[k]}
    if !newobj.empty?
      result = client.execute(:api_method => eval('arvados.' + rsc + '.update'),
                     :parameters => {"uuid" => uuid},
                     :body_object => { rsc.singularize => newobj },
                     :authenticated => false,
                     :headers => {
                       authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
                     })
      results = check_response result
      STDERR.puts "Updated object #{results['uuid']}"
    else
      STDERR.puts "Object is unchanged, did not update."
    end
  end

  exit 0
end

def arv_create client, arvados, global_opts, remaining_opts
  types = resource_types(arvados.discovery_document)
  create_opts = Trollop::options do
    opt :project_uuid, "Project uuid in which to create the object", :type => :string
    stop_on resource_types(arvados.discovery_document)
  end

  object_type = remaining_opts.shift
  if object_type.nil?
    abort "Missing resource type, must be one of #{types.join ', '}"
  end

  rsc = arvados.discovery_document["resources"].keys.select { |k| object_type == k.singularize }
  if rsc.empty?
    abort "Could not determine resource type #{object_type}"
  end
  rsc = rsc.first

  discovered_params = arvados.discovery_document["resources"][rsc]["methods"]["create"]["parameters"]
  method_opts = Trollop::options do
    banner head_banner
    banner "Usage: arv create [--project-uuid] #{object_type} [create parameters]"
    banner ""
    banner "This method supports the following parameters:"
    banner ""
    discovered_params.each do |k,v|
      opts = Hash.new()
      opts[:type] = v["type"].to_sym if v.include?("type")
      if [:datetime, :text, :object, :array].index opts[:type]
        opts[:type] = :string                       # else trollop bork
      end
      opts[:default] = v["default"] if v.include?("default")
      opts[:default] = v["default"].to_i if opts[:type] == :integer
      opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
      opts[:required] = true if v.include?("required") and v["required"]
      description = ''
      description = '  ' + v["description"] if v.include?("description")
      opt k.to_sym, description, opts
    end
  end

  initial_obj = {}
  if create_opts[:project_uuid]
    initial_obj["owner_uuid"] = create_opts[:project_uuid]
  end

  edit_and_commit_object initial_obj, "", global_opts do |newobj|
    result = client.execute(:api_method => eval('arvados.' + rsc + '.create'),
                   :parameters => method_opts,
                   :body_object => {object_type => newobj},
                   :authenticated => false,
                   :headers => {
                     authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
                   })
    results = check_response result
    puts "Created object #{results['uuid']}"
  end

  exit 0
end

def to_boolean(s)
  !!(s =~ /^(true|t|yes|y|1)$/i)
end

def head_banner
  "Arvados command line client\n"
end

def help_methods(discovery_document, resource, method=nil)
  banner = head_banner
  banner += "Usage: arv #{resource} [method] [--parameters]\n"
  banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
  banner += "The #{resource} resource supports the following methods:"
  banner += "\n\n"
  discovery_document["resources"][resource.pluralize]["methods"].
    each do |k,v|
    description = ''
    if v.include? "description"
      # add only the first line of the discovery doc description
      description = '  ' + v["description"].split("\n").first.chomp
    end
    banner += "   #{sprintf("%20s",k)}#{description}\n"
  end
  banner += "\n"
  STDERR.puts banner

  if not method.nil? and method != '--help' and method != '-h' then
    abort "Unknown method #{method.inspect} " +
                  "for resource #{resource.inspect}"
  end
  exit 255
end

def help_resources(option_parser, discovery_document, resource)
  option_parser.educate
  exit 255
end

def resource_types discovery_document
  resource_types = Array.new()
  discovery_document["resources"].each do |k,v|
    resource_types << k.singularize
  end
  resource_types
end

def parse_arguments(discovery_document, subcommands)
  resources_and_subcommands = resource_types(discovery_document) + subcommands

  option_parser = Trollop::Parser.new do
    version __FILE__
    banner head_banner
    banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
    banner ""
    banner "Available flags:"

    opt :dry_run, "Don't actually do anything", :short => "-n"
    opt :verbose, "Print some things on stderr"
    opt :format,
        "Set the output format. Must be one of json (default), yaml or uuid.",
        :type => :string,
        :default => 'json'
    opt :short, "Return only UUIDs (equivalent to --format=uuid)"

    banner ""
    banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
    banner ""
    banner "Available subcommands: #{subcommands.join(', ')}"
    banner ""

    banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"

    banner ""
    banner "Additional options:"

    conflicts :short, :format
    stop_on resources_and_subcommands
  end

  global_opts = Trollop::with_standard_exception_handling option_parser do
    o = option_parser.parse ARGV
  end

  unless %w(json yaml uuid).include?(global_opts[:format])
    $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
    $stderr.puts "Use #{$0} --help for more information."
    abort
  end

  if global_opts[:short]
    global_opts[:format] = 'uuid'
  end

  resource = ARGV.shift

  if not subcommands.include? resource
    if not resources_and_subcommands.include?(resource)
      puts "Resource or subcommand '#{resource}' is not recognized.\n\n" if !resource.nil?
      help_resources(option_parser, discovery_document, resource)
    end

    method = ARGV.shift
    if not (discovery_document["resources"][resource.pluralize]["methods"].
            include?(method))
      help_methods(discovery_document, resource, method)
    end

    discovered_params = discovery_document\
    ["resources"][resource.pluralize]\
    ["methods"][method]["parameters"]
    method_opts = Trollop::options do
      banner head_banner
      banner "Usage: arv #{resource} #{method} [--parameters]"
      banner ""
      banner "This method supports the following parameters:"
      banner ""
      discovered_params.each do |k,v|
        opts = Hash.new()
        opts[:type] = v["type"].to_sym if v.include?("type")
        if [:datetime, :text, :object, :array].index opts[:type]
          opts[:type] = :string                       # else trollop bork
        end
        opts[:default] = v["default"] if v.include?("default")
        opts[:default] = v["default"].to_i if opts[:type] == :integer
        opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
        opts[:required] = true if v.include?("required") and v["required"]
        description = ''
        description = '  ' + v["description"] if v.include?("description")
        opt k.to_sym, description, opts
      end

      body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
      if body_object and discovered_params[resource].nil?
        is_required = true
        if body_object["required"] == false
          is_required = false
        end
        opt resource.to_sym, "#{resource} (request body)", {
          required: is_required,
          type: :string
        }
      end
    end

    discovered_params.each do |k,v|
      k = k.to_sym
      if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
        if method_opts[k].andand.match /^\//
          method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
        end
      end
    end
  end

  return resource, method, method_opts, global_opts, ARGV
end

#
# ENTRY POINT
#

init_config

ENV['ARVADOS_API_VERSION'] ||= 'v1'

if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
  abort <<-EOS
ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
  EOS
end

# do this if you're testing with a dev server and you don't care about SSL certificate checks:
if ENV['ARVADOS_API_HOST_INSECURE']
  suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
end

begin
  client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
  arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
rescue Exception => e
  puts "Failed to connect to Arvados API server: #{e}"
  exit 1
end

# Parse arguments here
resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)

check_subcommands client, arvados, resource_schema, global_opts, remaining_opts

controller = resource_schema.pluralize

api_method = 'arvados.' + controller + '.' + method

if global_opts[:dry_run]
  if global_opts[:verbose]
    $stderr.puts "#{api_method} #{method_opts.inspect}"
  end
  exit
end

request_parameters = {_profile:true}.merge(method_opts)
resource_body = request_parameters.delete(resource_schema.to_sym)
if resource_body
  request_body = {
    resource_schema => resource_body
  }
else
  request_body = nil
end

case api_method
when
  'arvados.jobs.log_tail_follow'

  # Special case for methods that respond with data streams rather
  # than JSON (TODO: use the discovery document instead of a static
  # list of methods)
  uri_s = eval(api_method).generate_uri(request_parameters)
  Curl::Easy.perform(uri_s) do |curl|
    curl.headers['Accept'] = 'text/plain'
    curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
    if ENV['ARVADOS_API_HOST_INSECURE']
      curl.ssl_verify_peer = false
      curl.ssl_verify_host = false
    end
    if global_opts[:verbose]
      curl.on_header { |data| $stderr.write data }
    end
    curl.on_body { |data| $stdout.write data }
  end
  exit 0
else
  result = client.execute(:api_method => eval(api_method),
                          :parameters => request_parameters,
                          :body_object => request_body,
                          :authenticated => false,
                          :headers => {
                            authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
                          })
end

begin
  results = JSON.parse result.body
rescue JSON::ParserError => e
  abort "Failed to parse server response:\n" + e.to_s
end

if results["errors"] then
  abort "Error: #{results["errors"][0]}"
end

case global_opts[:format]
when 'json'
  puts Oj.dump(results, :indent => 1)
when 'yaml'
  puts results.to_yaml
else
  if results["items"] and results["kind"].match /list$/i
    results['items'].each do |i| puts i['uuid'] end
  elsif results['uuid'].nil?
    abort("Response did not include a uuid:\n" +
          Oj.dump(results, :indent => 1) +
          "\n")
  else
    puts results['uuid']
  end
end