# fastlane ios release \
#   key_id:77HLG2C29P \
#   issuer_id:a1ead579-73d7-4227-b9d6-1aeccf17edb4 \
#   key_filepath:AuthKey_77HLG2C29P.p8 \
#   app_identifier:com.fragorus.live \
#   team_id:785R8UTSWS






default_platform(:ios)
platform :ios do
  before_all do
    ENV['MATCH_PASSWORD'] = '123456'
  end

    # print given options
    desc "Print given options"
    lane :print_options do |options|
        UI.message("Options: #{options}")
    end


  desc "Release a new version"

  lane :release do |options|
    # Required options check
    required_options = %i[key_id issuer_id key_filepath app_identifier team_id]
    missing_options = required_options.select { |option| options[option].nil? }
    UI.user_error!("Missing required options: #{missing_options.join(', ')}") unless missing_options.empty?

    # Check .p8 file existence
    unless File.exist?("../#{options[:key_filepath]}")
      UI.user_error!("The .p8 file does not exist in the parent folder (should be in the ios folder)")
    end




    # Define App Store Connect API key
    api_key = app_store_connect_api_key(
      key_id: options[:key_id],
      issuer_id: options[:issuer_id],
      key_filepath: options[:key_filepath],
      in_house: false
    )

    # Manage keychain
    keychain_name = options[:app_identifier]
    keychain_password = "123456"
    unless File.exist?("~/Library/Keychains/#{keychain_name}-db")
      create_keychain(
        name: keychain_name,
        password: keychain_password,
        default_keychain: false,
        unlock: true,
        timeout: 0,
        lock_when_sleeps: false,
        add_to_search_list: true
      )
    end
    sh "security unlock-keychain -p #{keychain_password} ~/Library/Keychains/#{keychain_name}-db"

    # Branch cleanup in certificates repository
    branch_name = options[:app_identifier]
    sh <<-SHELL
      REPO_URL="https://eamon831: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@github.com/eamon831/certificates.git"
      if git ls-remote --heads $REPO_URL #{branch_name} | grep -q "refs/heads/#{branch_name}"; then
          echo "#{branch_name} branch exists. Deleting..."
          git clone $REPO_URL
          cd certificates
          git push origin --delete #{branch_name}
          cd ..
          rm -rf certificates
      else
         echo "#{branch_name} branch does not exist. Skipping deletion."
      fi
    SHELL

    # Provisioning and Code Signing
    match(
      type: "appstore",
      api_key: api_key,
      git_url: "https://github.com/eamon831/certificates.git",
      app_identifier: options[:app_identifier],
      force: true,
      keychain_name: "#{keychain_name}-db",
      keychain_password: keychain_password,
      git_branch: branch_name
    )

    # Sync code signing settings in Xcode project
    update_code_signing_settings(
      use_automatic_signing: false,
      path: "Runner.xcodeproj",
      team_id: options[:team_id],
      bundle_identifier: options[:app_identifier],
      code_sign_identity: "iPhone Distribution",
      sdk: "iphoneos*",
      profile_name: "match AppStore #{options[:app_identifier]}"
    )

    # Build the app
    gym(
      workspace: "Runner.xcworkspace",
      scheme: "Runner",
      export_method: "app-store",
      export_options: {
        provisioningProfiles: {
          options[:app_identifier] => "match AppStore #{options[:app_identifier]}"
        }
      },
      derived_data_path: "build",
      buildlog_path: "build",
    )

    # Upload to App Store
    deliver(
      api_key: api_key,
      ipa: "Runner.ipa",
      team_id: options[:team_id],
      app_identifier: options[:app_identifier],
      precheck_include_in_app_purchases: false,
      submit_for_review: false,
      automatic_release: false,
      skip_metadata: true,
      skip_screenshots: true,
      skip_binary_upload: false
    )

    # Delete temporary keychain
    delete_keychain(name: "#{keychain_name}-db")
  end
end
