#!/usr/bin/env ruby

require File.join(File.dirname(__FILE__), 'kraken_mobile_helpers')
require File.join(File.dirname(__FILE__), 'kraken_mobile_setup')
require File.join(File.dirname(__FILE__), 'kraken_mobile_calabash_android')
$LOAD_PATH << File.expand_path('../lib', __dir__)
require 'kraken_mobile'
require 'kraken-mobile/constants'

#-------------------------------
# AGV reader helper
#-------------------------------

def read_configuration
  configuration_command = ARGV.select do |arg|
    arg.include?('--configuration=')
  end.first
  return if configuration_command.nil?

  configuration_command = configuration_command.strip.downcase
  configuration_command.slice!('--configuration=')
  configuration_command
end

def read_user_entered_properties_path
  properties_command = ARGV.select { |arg| arg.include?('--properties=') }.first
  return if properties_command.nil?

  properties_command = properties_command.strip.downcase
  properties_command.slice!('--properties=')
  properties_command
end

#-------------------------------
# Helpers
#-------------------------------

def user_entered_apk_path
  return nil if ARGV.first.nil?

  first_argument = ARGV.first
  return nil if first_argument.start_with?('--') # Is argument parameter not apk

  File.expand_path(first_argument)
end

#-------------------------------
# Command reader
#-------------------------------

if ARGV.length.zero?
  print_usage
else
  cmd = ARGV.shift
  case cmd
  when 'version'
    require 'kraken-mobile/version'
    puts KrakenMobile::VERSION
  when 'devices'
    require 'kraken-mobile/helpers/devices_helper/manager'
    print_devices
  when 'setup'
    KrakenSetup.new.run
  when 'gen'
    ensure_java_installed
    ensure_android_sdk_installed

    scaffold_folder_structure
  when 'resign'
    ensure_java_installed
    ensure_android_sdk_installed

    require 'calabash-android/helpers'
    puts 'Resigning APK with Calabash-Android'
    ensure_apk_is_specified
    resign_apk(user_entered_apk_path)
  when 'run'
    ensure_java_installed
    ensure_android_sdk_installed

    require File.join(File.dirname(__FILE__), 'kraken_mobile_calabash_android')
    configuration = read_configuration
    user_entered_properties_path = read_user_entered_properties_path
    handle_calabash_android(configuration, user_entered_properties_path)
  else
    print_usage
  end
end