xcode_select '/Applications/Xcode_15.0.1.app'

default_platform(:ios)
APP_STORE_CONNECT_TEAM_ID = ENV["APP_STORE_CONNECT_TEAM_ID"]
APPLE_ISSUER_ID = ENV["APPLE_ISSUER_ID"]
APPLE_KEY_CONTENT = ENV["APPLE_KEY_CONTENT"]
APPLE_KEY_ID = ENV["APPLE_KEY_ID"]
TEAM_ID = ENV["INJI_IOS_DEVELOPER_PORTAL_TEAM_ID"]
FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD = ENV["INJI_IOS_FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"]
FASTLANE_USER= ENV["IOS_FASTLANE_APPLE_ID"]
PROVISIONING_PROFILE_SPECIFIER = ENV["INJI_IOS_PROVISIONING_PROFILE_SPECIFIER"]
TEMP_KEYCHAIN_USER = ENV["INJI_IOS_TEMP_KEYCHAIN_USER"]
TEMP_KEYCHAIN_PASSWORD = ENV["INJI_IOS_TEMP_KEYCHAIN_PASSWORD"]
GIT_AUTHORIZATION = ENV["GIT_AUTHORIZATION"]
SLACK_URL = ENV["SLACK_WEBHOOK_URL"]
APP_FLAVOR = ENV["APP_FLAVOR"]
MATCH_PASSWORD = ENV["MATCH_PASSWORD"]
FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT = "120"
TESTFLIGHT_INTERNAL_TESTERS_GROUP = ENV["TESTFLIGHT_INTERNAL_TESTERS_GROUP"]
TESTFLIGHT_BETA_APP_DESCRIPTION = ENV["TESTFLIGHT_BETA_APP_DESCRIPTION"]
DEVELOPER_APP_ID = ENV["DEVELOPER_APP_ID"]
MIMOTO_HOST = ENV["MIMOTO_HOST"]
ESIGNET_HOST =  ENV["ESIGNET_HOST"]
APPLICATION_THEME = ENV["APPLICATION_THEME"]
CREDENTIAL_REGISTRY_EDIT = ENV["CREDENTIAL_REGISTRY_EDIT"]

def generate_app_bundle_id()
  flavor = APP_FLAVOR
  case flavor
  when "residentapp"
    # the old app flavor
    return "io.mosip.inji.wallet.mobileid"
  when "inji"
    # io.mosip.inji is not available in iOS
    return "io.mosip.inji.wallet"
  when "collab"
    return "io.mosip.inji.mobile.collab"
  when "synergy"
    return "io.mosip.inji.mobile.synergy"
  when "mec"
    return "io.mosip.inji.mec"
  end
end

def map_flavour_tosuffix()
  flavor = APP_FLAVOR
  case flavor
  when "residentapp"
    return "wallet.mobileid"
  when "inji"
    return "wallet"
  when "collab"
    return "mobile.collab"
  when "synergy"
    return "mobile.synergy"
  when "mec"
    return "mec"
  end
  return flavor
end

def generate_app_name()
  flavor = APP_FLAVOR
  case flavor
  when "residentapp"
    return "MOSIP INJI APP"
  when "inji"
    return "Inji Wallet"
  when "collab"
    return "Inji Wallet Collab"
  when "synergy"
    return "Inji Wallet Synergy"
  when "mec"
    return "Inji Wallet Mec"
  end
end

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: 3600
  )
end

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


platform :ios do

  lane :ios_ui_automation_build 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}",
      duration: 1200,
      in_house: false,
      is_key_content_base64: true
    )
  
    match(
      type: 'appstore',
      app_identifier: "#{generate_app_bundle_id}",
      git_basic_authorization: Base64.strict_encode64("#{GIT_AUTHORIZATION}"),
      readonly: false,
      keychain_name: keychain_name,
      keychain_password: keychain_password,
      api_key: api_key
    )

    profile_mapping = Actions.lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING]

    gym(
      configuration: "Release",
      workspace: "Inji.xcworkspace",
      scheme: "Inji",
      export_method: "app-store",
      output_directory: "./fastlane/Inji_artifacts", 
      output_name: "#{generate_app_name}.ipa",
      export_options: {
        provisioningProfiles: {
          "#{generate_app_bundle_id}" => "match AppStore #{generate_app_bundle_id}"
        }
      }
    )
  
    delete_temp_keychain(keychain_name)
  end
  
  lane :beta 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}",
      duration: 1200,
      in_house: false,
      is_key_content_base64: true
    )

    version = get_version_number(xcodeproj: "Inji.xcodeproj")

    previous_build_number = latest_testflight_build_number(
      app_identifier: "#{generate_app_bundle_id}",
      api_key: api_key,
      version: version
    )

    current_build_number = previous_build_number + 1

    increment_build_number(
      xcodeproj: "Inji.xcodeproj",
      build_number: current_build_number
    )

    update_app_identifier(
      app_identifier: "#{generate_app_bundle_id}",
      plist_path: "Inji/Info.plist"
    )
    # replace bundle ID
    s = "s/wallet.mobileid/#{map_flavour_tosuffix}/g"
    sh("sed -i '' -e #{s} ../Inji.xcodeproj/project.pbxproj")

    # replace Product name
    p = "s|PRODUCT_NAME = Inji|PRODUCT_NAME = \"#{generate_app_name}\"|"
    sh ("sed -i '' -e '#{p}' ../Inji.xcodeproj/project.pbxproj")

    # update app display name
    update_info_plist(
      plist_path: 'Inji/Info.plist',
      display_name: "#{generate_app_name}"
    )

    # folder to copy artifacts to upload to github actions
    output_directory = "./Inji_artifacts"
    sh("mkdir -p '#{output_directory}'")

    match(
      type: 'appstore',
      app_identifier: "#{generate_app_bundle_id}",
      git_basic_authorization: Base64.strict_encode64("#{GIT_AUTHORIZATION}"),
      readonly: false,
      keychain_name: keychain_name,
      keychain_password: keychain_password,
      api_key: api_key
    )

    profile_mapping = Actions.lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING]

    gym(
      configuration: "Release",
      workspace: "Inji.xcworkspace",
      scheme: "Inji",
      export_method: "app-store",

      export_options: {
        provisioningProfiles: {
          "#{generate_app_bundle_id}" => "match AppStore #{generate_app_bundle_id}"
        }
      }
    )

    # copy IPA to the folder
    sh("cp -R '../#{generate_app_name}.ipa' '#{output_directory}'")

    pilot(
       app_identifier: "#{generate_app_bundle_id}",
       api_key: api_key,
       ipa: "./#{generate_app_name}.ipa",
       changelog: "#{TESTFLIGHT_BETA_APP_DESCRIPTION}",
       localized_build_info: {
          "default": {
            whats_new: "#{TESTFLIGHT_BETA_APP_DESCRIPTION}",
          }
      },
       skip_waiting_for_build_processing: false,
       distribute_external: true,
       submit_beta_review: false,
       groups: ["#{TESTFLIGHT_INTERNAL_TESTERS_GROUP}"],
    )

    delete_temp_keychain(keychain_name)

    archive_path = gym(
    skip_package_ipa: true,
    destination: "generic/platform=iOS Simulator",
    configuration: "Release",
    build_path: "./build",
    )

    # find and copy App file to the folder
    find_command = "find '../build/' -type d -name 'Products'"
    app_path = sh(find_command, log: false).strip
    sh("cp -R '#{app_path}' '#{output_directory}'")

    slack(
      message: "#{generate_app_name} #{version} (#{current_build_number}) is uploaded to testflight.",
      success: true,
      slack_url: "#{SLACK_URL}",
      default_payloads: [:git_branch, :last_git_commit]
    )

  end

  lane :ios_app_build do

    archive_path = gym(
    skip_package_ipa: true,
    destination: "generic/platform=iOS Simulator",
    configuration: "Release",
    build_path: "./build",
    )

   end
end