platform :android do

    desc "Publish the app to Huawei AppGallery"
    desc "#### Example:"
    desc "```\nfastlane android publish_app_gallery client_id:xxx client_secret:xxx app_id:xxx apk_path:xxx\n```"
    desc "#### Options"
    desc " * **`client_id`**: The client ID for Huawei AppGallery Connect"
    desc " * **`client_secret`**: The client secret for Huawei AppGallery Connect"
    desc " * **`app_id`**: The app ID for the application"
    desc " * **`apk_path`**: The path to the APK/AAB file"
    desc "#### Required environment variables"
    desc " * **`ANDROID_KEYSTORE_FILE`**: path the Android Keystore file"
    desc " * **`ANDROID_KEYSTORE_PASSWORD`**: Android Keystore password"
    desc " * **`ANDROID_KEY_PASSWORD`**: Android Keystore Key password"
    desc " * **`ANDROID_KEY_ALIAS`**: Android Keystore Key alias"
    desc ""
    lane :publish_app_gallery do |options|
        organization = organization!(options)

        bundle(organization: organization)

        huawei_appgallery_connect(
            client_id: options[:client_id],
            client_secret: options[:client_secret],
            app_id: options[:app_id],
            apk_path: options[:apk_path],
            delay_before_submit_for_review: 60,
            is_aab: true,
            submit_for_review: true,
        )
    end

    desc "Update Huawei AppGallery store listing information"
    desc "#### Example:"
    desc "```\nfastlane android update_app_gallery client_id:xxx client_secret:xxx app_id:xxx \n```"
    desc "#### Options"
    desc " * **`client_id`**: The client ID for Huawei AppGallery Connect"
    desc " * **`client_secret`**: The client secret for Huawei AppGallery Connect"
    desc " * **`app_id`**: The app ID for the application"
    desc ""
    lane :update_app_gallery do |options|
        organization = organization!(options)

        huawei_appgallery_connect_update_app_localization(
            client_id: options[:client_id],
            client_secret: options[:client_secret],
            app_id: options[:app_id],
            metadata_path: "fastlane/metadata/huawei",
        )
    end

    desc "Publish a new version of the app on Google Play"
    desc "#### Example:"
    desc "```\nfastlane android publish track:alpha version_code:100 organization:ooni json_key:key.json\n```"
    desc "#### Options"
    desc " * **`track`**: internal, alpha, beta, production"
    desc " * **`organization`**: ooni, dw"
    desc " * **`version_code`**: new version code"
    desc " * **`json_key`**: path to Google Play service account JSON file"
    desc "#### Required environment variables"
    desc " * **`ANDROID_KEYSTORE_FILE`**: path the Android Keystore file"
    desc " * **`ANDROID_KEYSTORE_PASSWORD`**: Android Keystore password"
    desc " * **`ANDROID_KEY_PASSWORD`**: Android Keystore Key password"
    desc " * **`ANDROID_KEY_ALIAS`**: Android Keystore Key alias"
    desc ""
    lane :publish do |options|
        organization = organization!(options)

        bundle(organization: organization)

        upload_to_play_store(
            package_name: package_name(organization),
            track: options[:track],
            version_code: options[:version_code],
            metadata_path: metadata_path(organization),
            json_key: options[:json_key],
            skip_upload_metadata: true,
            skip_upload_changelogs: false,
            skip_upload_apk: true, # we're uploading AAB
            skip_upload_images: true,
            skip_upload_screenshots: true,
        )
    end

    desc "Create AAB file"
    desc "#### Example:"
    desc "```\nfastlane android bundle organization:ooni\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc "#### Required environment variables"
    desc " * **`ANDROID_KEYSTORE_FILE`**: path the Android Keystore file"
    desc " * **`ANDROID_KEYSTORE_PASSWORD`**: Android Keystore password"
    desc " * **`ANDROID_KEY_PASSWORD`**: Android Keystore Key password"
    desc " * **`ANDROID_KEY_ALIAS`**: Android Keystore Key alias"
    desc ""
    lane :bundle do |options|
        gradle(task: "copyBrandingToCommonResources bundleFullRelease -Porganization=#{options[:organization]}")
    end

    desc "Promote Google Play release"
    desc "#### Example:"
    desc "```\nfastlane android promote organization:ooni track:alpha promote_track:beta rollout:0.5 json_key:key.json\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc " * **`current_track`**: internal, alpha, beta, production"
    desc " * **`promote_track`**: alpha, beta, production (optional to just update rollout)"
    desc " * **`rollout`**: set or update rollout [0 to 1] (optional, defaults to 1)"
    desc " * **`json_key`**: path to Google Play service account JSON file"
    desc ""
    lane :promote do |options|
        organization = organization!(options)

        upload_to_play_store(
            package_name: package_name(organization),
            track: options[:current_track],
            track_promote_to: ((options[:promote_track].nil? or options[:promote_track].empty?) ? nil : options[:promote_track]),
            # The percentage of the user fraction when uploading to the rollout track (setting to 1 will complete the rollout)
            rollout: ((options[:rollout].nil? or options[:rollout].empty?) ? '1' : options[:rollout]),
            metadata_path: metadata_path(organization),
            json_key: options[:json_key],
            skip_upload_apk: true,
            skip_upload_aab: true,
            skip_upload_images: true,
            skip_upload_metadata: true,
            skip_upload_screenshots: true,
            skip_upload_changelogs: true,
        )
    end

    desc "Capture screenshots for Google Play"
    desc "#### Example:"
    desc "```\nfastlane android capture_screens organization:ooni locales:en,it\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc " * **`locales`**: comma-separated list of locales (optional, defaults to full list based on the organization)"
    desc ""
    lane :capture_screens do |options|
        organization = organization!(options)
        locales = locales_or_default(options)

        gradle(task: "clean copyBrandingToCommonResources assembleFullDebug assembleFullDebugAndroidTest -Porganization=#{organization}")

        enable_demo_mode
        capture_android_screenshots(
            app_package_name: package_name(organization, debug: true),
            locales: locales,
            output_directory: metadata_path(organization),
            clear_previous_screenshots: false
        )
    end

    desc "Update Google Play store listing information"
    desc "#### Example:"
    desc "```\nfastlane android update_google_play organization:ooni screenshots:true metadata:true json_key:key.json\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc " * **`screenshots`**: true or false (default false)"
    desc " * **`metadata`**: true or false (default false)"
    desc " * **`json_key`**: path to Google Play service account JSON file"
    desc ""
    lane :update_google_play do |options|
        organization = organization!(options)

        upload_to_play_store(
            package_name: package_name(organization),
            metadata_path: metadata_path(organization),
            json_key: options[:json_key],
            skip_upload_apk: true,
            skip_upload_aab: true,
            skip_upload_images: true,
            skip_upload_changelogs: true,
            skip_upload_metadata: options[:metadata] != true && options[:metadata] != 'true',
            skip_upload_screenshots: options[:screenshots] != true && options[:screenshots] != 'true',
        )
    end

    private_lane :enable_demo_mode do
        # Enable demo mode before running screengrab
        adb_command = "adb shell settings put global sysui_demo 1"
        Action.sh(adb_command)

        # Set demo mode properties
        demo_commands = [
            "enter",
            "battery level 100",
            "battery plug false",
            "network wifi level 4",
            "network mobile hidden",
            "clock 0800",
            "notifications remove",
            "status bar icons"
        ]

        demo_commands.each do |cmd|
            Action.sh("adb shell am broadcast -a com.android.systemui.demo -e command #{cmd}")
        end
    end
end

platform :ios do
    desc "Build iOS app"
    desc "#### Example:"
    desc "```\nfastlane ios build organization:ooni\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc ""
    lane :build do |options|
        organization = organization!(options)

        scheme = scheme!(organization)

        gradle(task: "podInstall -Porganization=#{organization}")
        cocoapods(podfile: "./iosApp/Podfile")

        puts "Building #{scheme}"
        sh "cd .. && echo \"organization=#{organization}\" >> gradle.properties"
        sh "cd .. && xcodebuild -workspace iosApp/iosApp.xcworkspace -scheme '#{scheme}' -destination='name=Any iOS Device' -sdk iphoneos archive CODE_SIGNING_ALLOWED='NO' -archivePath iosApp/build/#{scheme}.xcarchive | xcpretty"
        # sh "cd .. && xcodebuild -exportArchive -archivePath iosApp/build/#{scheme}.xcarchive  -exportPath iosApp/build/#{scheme}.ipa -exportOptionsPlist iosApp/#{scheme}.exportOptions.plist"
    end

    desc "Publish iOS app"
    desc "#### Example:"
    desc "```\nfastlane ios publish organization:ooni\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc ""
    lane :publish do |options|
        organization = organization!(options)
        scheme = scheme!(organization)
        build(organization: organization)
#         upload_to_app_store(
#           ipa: "iosApp/build/#{scheme}.ipa"
#         )
        # TODO
    end

    desc "Update Apple App Store information"
    desc "#### Example:"
    desc "```\nfastlane android update_app_store organization:ooni screenshots:true metadata:true\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc " * **`screenshots`**: true or false (default false)"
    desc " * **`metadata`**: true or false (default false)"
    desc ""
    lane :update_app_store do |options|
        # TODO
    end

    desc "Capture screenshots for Apple App Store"
    desc "#### Example:"
    desc "```\nfastlane ios capture_screens organization:ooni locales:en,it\n```"
    desc "#### Options"
    desc " * **`organization`**: ooni, dw"
    desc " * **`locales`**: comma-separated list of locales (optional, defaults to full list based on the organization)"
    desc ""
    lane :capture_screens do |options|
        organization = organization!(options)
        locales = locales_or_default(options)
        scheme = scheme!(organization)

        capture_screenshots(
            workspace: "iosApp/iosApp.xcworkspace",
            output_directory: "fastlane/metadata/#{organization}/ios",
            scheme: "#{scheme}UITests",
            test_target_name: scheme,
            erase_simulator: true,
            languages: locales,
            override_status_bar_arguments: "--time 12:00 --batteryState charging",
        )
    end


    desc "Upload debug symbols to Sentry"
    desc "#### Example:"
    desc "```\nfastlane sentry_upload_debug_symbols auth_token:... org_slug:ooni project_slug:probe-multiplatform-ios path:.\n```"
    desc "#### Options"
    desc " * **`auth_token`**: Sentry auth token"
    desc " * **`org_slug`**: Sentry organization slug"
    desc " * **`project_slug`**: Sentry project slug"
    desc ""
    lane :sentry_upload_debug_symbols do |options|

        sentry_debug_files_upload(
            auth_token: options[:auth_token],
            org_slug: options[:org_slug],
            project_slug: options[:project_slug],
            path: options[:path] || '.'
        )
    end
end


def organization!(options)
    organization = options[:organization]
    raise "Invalid organization '#{organization}'" unless %w(ooni dw).include?(organization)
    return organization
end

def scheme!(organization)
    case organization
    when "ooni" then "OONIProbe"
    when "dw" then "NewsMediaScan"
    end
end

def metadata_path(organization)
    "./fastlane/metadata/#{organization}/android"
end

def package_name(organization, debug: false)
    case organization
    when "ooni" then "org.openobservatory.ooniprobe"
    when "dw" then "com.dw.ooniprobe"
    end + (debug ? '.dev' : '')
end

def locales_or_default(options)
   if options[:locales]
       options[:locales].split(',')
   else
       case options[:organization]
       when "ooni" then ['ar', 'en-US', 'hi-IN', 'pt-BR', 'sk', 'zh-CN', 'ca', 'es-ES', 'id', 'ro', 'sq', 'zh-TW', 'de-DE', 'fa', 'is-IS', 'ru-RU', 'th', 'el-GR', 'fr-FR', 'it-IT', 'tr-TR']
       when "dw" then ['en-US', 'de-DE', 'es-ES', 'fr-FR', 'pt-BR', 'ru', 'tr-TR']
       end
   end
end
