require "shellwords"
require "fileutils"

default_platform(:ios)

def ios_root
  @ios_root ||= File.expand_path("..", __dir__)
end

def app_path(*parts)
  File.join(ios_root, "App", *parts)
end

def app_store_api_key!
  app_store_connect_api_key(
    key_id: ENV.fetch("APP_STORE_CONNECT_KEY_ID"),
    issuer_id: ENV.fetch("APP_STORE_CONNECT_ISSUER_ID"),
    key_content: ENV.fetch("APP_STORE_CONNECT_PRIVATE_KEY_BASE64"),
    is_key_content_base64: true,
    duration: 1200
  )
end

def write_export_options_plist(path:, team_id:, bundle_id:, profile_name:, sign_identity:)
  File.write(
    path,
    <<~PLIST
      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>destination</key>
        <string>export</string>
        <key>manageAppVersionAndBuildNumber</key>
        <false/>
        <key>method</key>
        <string>app-store-connect</string>
        <key>provisioningProfiles</key>
        <dict>
          <key>#{bundle_id}</key>
          <string>#{profile_name}</string>
        </dict>
        <key>signingCertificate</key>
        <string>#{sign_identity}</string>
        <key>signingStyle</key>
        <string>manual</string>
        <key>stripSwiftSymbols</key>
        <true/>
        <key>teamID</key>
        <string>#{team_id}</string>
        <key>uploadSymbols</key>
        <true/>
      </dict>
      </plist>
    PLIST
  )
end

platform :ios do
  desc "Build a signed App Store IPA"
  lane :build_release do |options|
    bundle_id = options[:bundle_id] || ENV.fetch("IOS_BUNDLE_ID", "com.monkeycode.mobile")
    profile_name = options[:profile_name] || ENV["IOS_PROFILE_NAME"]
    team_id = options[:team_id] || ENV["IOS_TEAM_ID"]
    output_name = options[:output_name] || ENV.fetch("IOS_OUTPUT_NAME", "MonkeyCode-ios.ipa")
    sign_identity = options[:sign_identity] || ENV.fetch("IOS_CODE_SIGN_IDENTITY", "Apple Distribution")

    UI.user_error!("IOS_PROFILE_NAME is required") if profile_name.to_s.empty?
    UI.user_error!("IOS_TEAM_ID is required") if team_id.to_s.empty?

    output_dir = app_path("output")
    archive_path = File.join(output_dir, "App.xcarchive")
    export_path = File.join(output_dir, "export")
    export_options_path = File.join(output_dir, "ExportOptions.plist")

    FileUtils.rm_rf(export_path)
    FileUtils.mkdir_p(output_dir)
    write_export_options_plist(
      path: export_options_path,
      team_id: team_id,
      bundle_id: bundle_id,
      profile_name: profile_name,
      sign_identity: sign_identity
    )

    update_code_signing_settings(
      path: app_path("App.xcodeproj"),
      use_automatic_signing: false,
      team_id: team_id,
      targets: ["App"],
      bundle_identifier: bundle_id,
      profile_name: profile_name,
      code_sign_identity: sign_identity
    )

    sh(
      [
        "xcodebuild",
        "-workspace", app_path("App.xcworkspace"),
        "-scheme", "App",
        "-configuration", "Release",
        "-archivePath", archive_path,
        "archive",
      ].shelljoin
    )

    sh(
      [
        "xcodebuild",
        "-exportArchive",
        "-archivePath", archive_path,
        "-exportPath", export_path,
        "-exportOptionsPlist", export_options_path,
      ].shelljoin
    )

    ipa_path = Dir[File.join(export_path, "*.ipa")].first
    UI.user_error!("No IPA was produced in #{export_path}") if ipa_path.to_s.empty?

    final_ipa_path = File.join(output_dir, output_name)
    FileUtils.cp(ipa_path, final_ipa_path)
  end

  desc "Upload an existing IPA to TestFlight"
  lane :upload_testflight do |options|
    ipa_path = options[:ipa] || ENV["IOS_IPA_PATH"]
    skip_waiting = options[:skip_waiting_for_build_processing]
    skip_waiting = true if skip_waiting.nil?

    UI.user_error!("An IPA path is required") if ipa_path.to_s.empty?

    upload_to_testflight(
      api_key: app_store_api_key!,
      ipa: ipa_path,
      skip_waiting_for_build_processing: skip_waiting
    )
  end

  desc "Upload an existing IPA and submit it to App Store review"
  lane :submit_app_store do |options|
    ipa_path = options[:ipa] || ENV["IOS_IPA_PATH"]

    UI.user_error!("An IPA path is required") if ipa_path.to_s.empty?

    upload_to_app_store(
      api_key: app_store_api_key!,
      ipa: ipa_path,
      skip_metadata: true,
      skip_screenshots: true,
      submit_for_review: true,
      automatic_release: false,
      force: true,
      precheck_include_in_app_purchases: false,
      submission_information: {
        export_compliance_uses_encryption: false
      }
    )
  end
end
