# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:android)

platform :android do
  before_all do
    ENV["KEYSTORE_DIR"] = ENV["PWD"] + "/keystores/"
  end

  desc "Assemble debug APKs."
  lane :assembleDebugApks do |options|
    gradle(
      tasks: ["assembleDebug"],
    )
  end

  desc "Assemble FDroid release APK"
  lane :assembleFDroidReleaseApk do |options|
    buildAndSignBitwarden(
      taskName: "assemble",
      flavor: "Fdroid",
      buildType: "Release",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Assemble F-Droid Beta APK"
  lane :assembleFDroidBetaApk do |options|
    buildAndSignBitwarden(
      taskName: "assemble",
      flavor: "Fdroid",
      buildType: "Beta",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Assemble Play Store release APK"
  lane :assemblePlayStoreReleaseApk do |options|
    buildAndSignBitwarden(
      taskName: "assemble",
      flavor: "Standard",
      buildType: "Release",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Assemble Play Store release APK"
  lane :assemblePlayStoreBetaApk do |options|
    buildAndSignBitwarden(
      taskName: "assemble",
      flavor: "Standard",
      buildType: "Beta",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Bundle Play Store release"
  lane :bundlePlayStoreRelease do |options|
    buildAndSignBitwarden(
      taskName: "bundle",
      flavor: "Standard",
      buildType: "Release",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Bundle Play Store release"
  lane :bundlePlayStoreBeta do |options|
    buildAndSignBitwarden(
      taskName: "bundle",
      flavor: "Standard",
      buildType: "Beta",
      storeFile: options[:storeFile],
      storePassword: options[:storePassword],
      keyAlias: options[:keyAlias],
      keyPassword: options[:keyPassword],
    )
  end

  desc "Runs Standard Debug tests and generates Kover report"
  lane :check do
    gradle(
        tasks: ["testStandardDebug", "lintStandardDebug", "detekt", "koverXmlReportStandardDebug"]
    )
  end

  desc "Apply build version information"
  fastlane_require "time"
  lane :setBuildVersionInfo do |options|

    # Read-in app build config file.
    buildConfigPath = "../app/build.gradle.kts"
    buildConfigFile = File.open(buildConfigPath)
    buildConfigText = buildConfigFile.read
    buildConfigFile.close

    currentVersionCode = buildConfigText.match(/versionCode = (\d+)/).captures[0]
    currentVersionName = buildConfigText.match(/versionName = "(.+)"/).captures[0]

    if options[:versionName].nil? or options[:versionName].to_s.empty?
        puts "Fetching latest tags from origin..."
        `git fetch --prune --no-recurse-submodules --filter=tree:0 --depth=1 --tags origin`
        puts "Getting latest version name from previous git tag..."
        latestTag = `git describe --tags $(git rev-list --tags --max-count=1)`.chomp()
        puts "Using tag #{latestTag} to calculate version name..."
        latestTag.slice!(0)
        puts "Current version name resolved to #{latestTag}."

        versionParts = latestTag.split(".")
        currentMajor = versionParts[0]
        currentMinor = versionParts[1]
        currentRevision = versionParts[2]

        currentDate = Time.new
        major = currentDate.year.to_s
        minor = currentDate.strftime "%-m"

        revision = 0
        if currentMajor == major and currentMinor == minor
            revision = currentRevision.to_i + 1
        end
        nextVersionName = "#{major}.#{minor}.#{revision}"
    else
        nextVersionName = options[:versionName].to_s
    end

    # Replace version information.
    puts "Setting version code to #{options[:versionCode]}."
    buildConfigText.gsub!("versionCode = #{currentVersionCode}", "versionCode = #{options[:versionCode]}")
    puts "Setting version name to #{nextVersionName}."
    buildConfigText.gsub!("versionName = \"#{currentVersionName}\"", "versionName = \"#{nextVersionName}\"")

    # Save changes
    File.open(buildConfigPath, "w") { |buildConfigFile| buildConfigFile << buildConfigText }
  end
  
  desc "Generate artifacts for the given [build] signed with the provided [keystore] and credentials."
  private_lane :buildAndSignBitwarden do |options|
    gradle(
      task: options[:taskName],
      flavor: options[:flavor],
      build_type: options[:buildType],
      properties: {
        "android.injected.signing.store.file" => ENV["KEYSTORE_DIR"] + options[:storeFile],
        "android.injected.signing.store.password" => options[:storePassword],
        "android.injected.signing.key.alias" => options[:keyAlias],
        "android.injected.signing.key.password" => options[:keyPassword]
      },
      print_command: false,
    )
  end

  desc "Publish Release Play Store artifacts to Firebase App Distribution"
  lane :distributeReleasePlayStoreToFirebase do |options|
    releaseNotes = generateReleaseNotes(
      repoName: "android",
      actionUrl: "#{options[:actionUrl]}"
    )
    firebase_app_distribution(
      app: "1:64530857057:android:f8d67b786db1b844",
      android_artifact_type: "APK",
      android_artifact_path: "app/build/outputs/apk/standard/release/com.x8bit.bitwarden-standard-release.apk",
      service_credentials_file: options[:service_credentials_file],
      groups: "internal-prod-group, livefront",
      release_notes: "#{releaseNotes}",
    )
  end

  desc "Publish Beta Play Store artifacts to Firebase App Distribution"
  lane :distributeBetaPlayStoreToFirebase do |options|
    releaseNotes = generateReleaseNotes(
      repoName: "android",
      actionUrl: "#{options[:actionUrl]}"
    )
    firebase_app_distribution(
      app: "1:64530857057:android:54c1ae56b269b959887e20",
      android_artifact_type: "APK",
      android_artifact_path: "app/build/outputs/apk/standard/beta/com.x8bit.bitwarden-standard-beta.apk",
      service_credentials_file: options[:service_credentials_file],
      groups: "internal-prod-group, livefront",
      release_notes: "#{releaseNotes}",
    )
  end

  desc "Publish Release F-Droid artifacts to Firebase App Distribution"
  lane :distributeReleaseFDroidToFirebase do |options|
    releaseNotes = generateReleaseNotes(
        repoName: "android",
        actionUrl: "#{options[:actionUrl]}"
    )
    firebase_app_distribution(
      app: "1:439897860529:android:b143708734b99c0e3fb590",
      android_artifact_type: "APK",
      android_artifact_path: "app/build/outputs/apk/fdroid/release/com.x8bit.bitwarden-fdroid-release.apk",
      service_credentials_file: options[:service_credentials_file],
      groups: "internal-prod-group, livefront",
      release_notes: "#{releaseNotes}"
    )
  end

  desc "Publish Play Store Beta bundle to Google Play Store"
  lane :publishBetaToPlayStore do
    upload_to_play_store(
      package_name: "com.x8bit.bitwarden.beta",
      track: "internal",
      release_status: "completed",
      rollout: "1",
      aab: "app/build/outputs/bundle/standardBeta/com.x8bit.bitwarden-standard-beta.aab",
    )
  end

  desc "Generate release notes"
  lane :generateReleaseNotes do |options|
    branchName = `git rev-parse --abbrev-ref HEAD`.chomp()
    releaseNotes = changelog_from_git_commits(
      commits_count: 1,
      pretty: "%s%n#{options[:repoName]}/#{branchName} @ %h %n %n#{options[:actionUrl]}"
    )
    releaseNotes
  end
end
