require 'json'
require 'fileutils'

default_platform(:ios)

package = JSON.parse(File.read('../package.json'))

platform :ios do
  setup_ci
  desc "Build the production iOS app"
  lane :release do |options|
    match(type: "appstore", readonly: true)
    api_key = app_store_connect_api_key(
      key_id: ENV["APP_STORE_KEY_ID"],
      issuer_id: ENV["APP_STORE_ISSUER_ID"],
      key_filepath: "apps/mobile/ios/authkey.p8"
    )
    build_app(
        workspace: "apps/mobile/ios/App/App.xcworkspace",
        scheme: "App",
        output_directory: "apps/mobile/dist/ios",
        output_name: "lyricistant.ipa"
    )
    if options[:deploy]
      upload_to_app_store(
        metadata_path: "./fastlane/metadata/ios",
        submit_for_review: true,
        force: true,
        overwrite_screenshots: true,
        precheck_include_in_app_purchases: false,
        submission_information: {
          add_id_info_uses_idfa: false,
          export_compliance_uses_encryption: false,
          content_rights_contains_third_party_content: false
        }
      )
    end
  end
end

platform :android do
  desc "Build the production Android app"
  lane :release do |options|
    gradle(
        project_dir: "apps/mobile/android/",
        task: ":app:clean :app:assembleRelease"
    )
    copy_artifacts(
      target_path: "apps/mobile/dist/android/",
      artifacts: ["apps/mobile/android/app/build/outputs/apk/release/app-release.apk"],
      fail_on_missing: true
    )
    Dir.chdir("..") do
      File.rename("apps/mobile/dist/android/app-release.apk", "apps/mobile/dist/android/lyricistant.apk")
    end
    if options[:deploy]
        upload_to_play_store(
          apk: "apps/mobile/dist/android/lyricistant.apk",
          metadata_path: "./fastlane/metadata/android",
          rollout: "1"
        )
    end
  end
end
