require 'json'

fastlane_version "1.60.0"

default_platform :android

platform :android do
  before_all do
    # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
  end

  desc "Runs all the tests"
  lane :test do
    gradle(task: "test")
    postToSlack()
  end

  desc "Submit a new Beta Build to Crashlytics Beta"
  lane :internal do
    setupBuildInfo()    

    commit = last_git_commit
    
    gradle(task: "assembleRelease")    

    notes = commit[:author] + commit[:message]

    puts notes

    crashlytics(
       notes: notes,
       groups: ['internal+'],
       api_token: "ENV['CRASHLYTICS_API']",
       build_secret: "ENV['CRASHLYTICS_SECRET']")

    manifest_analyzer(manifest_file: 'app/AndroidManifest.xml')
    
    if ENV['AWS_ACCESS_KEY_ID'] && ENV['AWS_SECRET_ACCESS_KEY']
      s3_url = upload_s3_file(file: Actions.lane_context[Actions::SharedValues::GRADLE_APK_OUTPUT_PATH],
        bucket: '',
        path: 'builds/mobile/android/internal/' + Actions.lane_context[SharedValues::MANIFEST_VERSION_NUM],
        s3_file_name: 'RunKeeper.apk')
      
      puts s3_url

      postToSlack("Internal Android build complete", '#koality-control', s3_url, "Android APK")
    else
	end
         

  end

  desc "Deploy a new version to the Google Play"
  lane :deploy do
    setupBuildInfo()
    gradle(task: "assembleRelease")
    supply
    postToSlack()
  end

  desc "Deploy a new beta version to the Google Play"
  lane :beta do
    setupBuildInfo()
    gradle(task: "assembleRelease")
    supply(track: "beta")

    if ENV['S3_ACCESS_KEY'] && ENV['S3_SECRET_ACCESS_KEY']
      s3_url = upload_s3_file(file: :apk_path,
        access_key: ENV['S3_ACCESS_KEY'],
        secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
        bucket: '',
        path: 'builds/mobile/android/beta/' + Actions.lane_context[SharedValues::MANIFEST_VERSION_NUM],
        s3_file_name: 'RunKeeper.apk')
      postToSlack("Internal Android Beta complete", '#android', s3_url, "Android APK")
    else
      postToSlack("Internal Android Beta complete", '#android')
    end 
 end


  error do |lane, exception|
    if ENV["SLACK_URL"]
      slack(
        message: exception.message,
        success: false
      )
    end
  end

  #Custom functions
#------------------------------------------------------------------------------------
  # Adds build information to plist to display in app
  def setupBuildInfo()

    print "Setting up build info"

    time = Time.now.strftime("%m/%d/%Y %H:%M")
    commit = `git rev-parse HEAD`
    commit = commit.gsub('\n', '')
    commit = commit.gsub('\t', '')

    print "commitMessage = " + last_git_commit[:message]
    print "branch = " + git_branch    
    print "buildDate = " + time
    print "currentCommit = " + commit

    buildInfo = {
        "currentCommit" => commit.strip,
        "branch" => git_branch.strip,
        "commitMessage" => last_git_commit[:message].strip,
        "buildDate" => time.strip,
        "bitriseBuildNumber" => ENV["BITRISE_BUILD_NUMBER"]
    }

    File.open("../app/res/raw/build_info.json","w") do |f|
      f.write(buildInfo.to_json)
    end

  end

  # Posts a message to slack potentially with a file
  def postToSlack(message = nil, channel = nil, s3_url = nil, url_title = nil)

    if ENV["SLACK_URL"]

      if s3_url != nil && url_title != nil
        slack(
          message: "Build Number " + ENV["BITRISE_BUILD_NUMBER"] + ' ' + message,
          success: true,
          channel: channel,
          default_payloads: [:test_result, :git_branch],
          attachment_properties: { # Optional, lets you specify any other properties available for attachments in the slack API (see https://api.slack.com/docs/attachments). This hash is deep merged with the existing properties set using the other properties above. This allows your own fields properties to be appended to the existings fields that were created using the `payload` property for instance.
            fields: [{
              title: url_title,
              value: s3_url,
              short: true
            }]
          }        
        )
      else
        slack(
          message: "Build Number " + ENV["BITRISE_BUILD_NUMBER"] + ' ' + message,
          channel: channel,
          success: true,
          default_payloads: [:test_result, :git_branch]       
        )
      end
    end
end
end