# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane
DEVELOPER_APP_IDENTIFIER = ENV["DEVELOPER_APP_IDENTIFIER"]

TEMP_KEYCHAIN_USER = ENV["TEMP_KEYCHAIN_USER"]
TEMP_KEYCHAIN_PASSWORD = ENV["TEMP_KEYCHAIN_PASSWORD"]

APPLE_ISSUER_ID = ENV["APPLE_ISSUER_ID"]
APPLE_KEY_ID = ENV["APPLE_KEY_ID"]
APPLE_KEY_CONTENT = ENV["APPLE_KEY_CONTENT"]

def delete_temp_keychain(name)
  delete_keychain(
    name: name
  ) if File.exist? File.expand_path("~/Library/Keychains/#{name}-db")
end

def create_temp_keychain(name, password)
  create_keychain(
    name: name,
    password: password,
    unlock: false,
    timeout: 0
  )
end

def ensure_temp_keychain(name, password)
  delete_temp_keychain(name)
  create_temp_keychain(name, password)
end

# default_platform(:ios)

platform :ios do
  desc "run iOS DevCycle tests"
  lane :tests do
    run_tests(
      derived_data_path: "~/Library/Developer/Xcode/DerivedData",
      buildlog_path: "./fastlane/fastlane-buildlog",
      scheme: "DevCycle",
      workspace: "DevCycle.xcworkspace",
      result_bundle: true
    )
  end
end

platform :tvos do
  desc "run tvOS DevCycle tests"
  lane :tests do
    run_tests(
      derived_data_path: "~/Library/Developer/Xcode/DerivedData",
      buildlog_path: "./fastlane/fastlane-buildlog",
      scheme: "DevCycle",
      workspace: "DevCycle.xcworkspace",
      result_bundle: true
    )
  end
end

platform :watchos do
  desc "run watchOS DevCycle tests"
  lane :tests do
    run_tests(
      derived_data_path: "~/Library/Developer/Xcode/DerivedData",
      buildlog_path: "./fastlane/fastlane-buildlog",
      scheme: "DevCycle",
      result_bundle: true
    )
  end
end

platform :mac do
  desc "run mac DevCycle tests"
  lane :tests do
    keychain_name = TEMP_KEYCHAIN_USER
    keychain_password = TEMP_KEYCHAIN_PASSWORD
    ensure_temp_keychain(keychain_name, keychain_password)

    api_key = app_store_connect_api_key(
      key_id: APPLE_KEY_ID,
      issuer_id: APPLE_ISSUER_ID,
      key_content: APPLE_KEY_CONTENT.gsub('\n', '\\n'),            
      duration: 1200,            
      in_house: false
    )

    match(
      type: 'appstore',
      app_identifier: "#{DEVELOPER_APP_IDENTIFIER}",
      readonly: true,
      keychain_name: keychain_name,
      keychain_password: keychain_password,
      api_key: api_key
    )

    scan(
      scheme: "DevCycle",
      workspace: "DevCycle.xcworkspace",
      destination: "platform=macOS"
    )

    delete_temp_keychain(keychain_name)
  end
end
