fastlane_version "1.50.0"
default_platform :ios

#platform :ios do
  before_all do
    #cocoapods
   #increment_build_number
  end

#Lanes
#------------------------------------------------------------------------------------  
  #desc "Runs all the tests"  
  lane :test do
    matchSetup(type: "development")
    scan(scheme: "RunKeeper Pro", device: "iPhone 6s 9.0")
    bundle_version = get_info_plist_value(path: 'Info.plist', key: "CFBundleShortVersionString")
    print bundle_version
    
  end

  lane :screenshots do |variable|
    snapshot    
    git_add(path:"fastlane/screenshots/")
    Actions.sh("git commit -m 'Screenshots added'")

    push_to_git_remote(
      remote: 'origin',         # optional, default: 'origin'
      local_branch: git_branch,  # optional, aliased by 'branch', default: 'master'
      remote_branch: git_branch, # optional, default is set to local_branch
      force: true,              # optional, default: false
    )
  end

  #desc "creates and uploads a build to testflight"

   lane :testflight do
    matchSetup(type: "appstore")
   
    increment_build_number({
      build_number: latest_testflight_build_number + 1
      })

    build(scheme: "RunKeeper Pro")
    
    pilot()

    if ENV['S3_ACCESS_KEY'] && ENV['S3_SECRET_ACCESS_KEY']
      bundle_version = get_info_plist_value(path: 'Info.plist', key: 'CFBundleShortVersionString')

      s3_url = upload_s3_file(file: '../Runkeeper.ipa',
      access_key: ENV['S3_ACCESS_KEY'],
      secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
      bucket: '',
      path: 'builds/mobile/iPhone/beta/' + bundle_version,
      s3_file_name: 'Runkeeper.ipa')

      postToSlack("iOS Build TestFlight submitted", s3_url, "iOS S3 Build")
    else
      postToSlack("iOS Build TestFlight submitted")
    end   
  end


  

  #desc "Use this lane to build via bitrise.io"
  lane :internal do
    matchSetup(type: "adhoc")
  
    increment_build_number(
      build_number: ENV["BITRISE_BUILD_NUMBER"] + '-' + git_branch
      )
    
    build(
      scheme: "RunKeeper Pro (AdHoc)"
    )    
   
    commit = last_git_commit

    crashlytics(
      ipa_path: "../RunKeeper.ipa",
      notes: git_branch + ' ' + commit[:author] + ' ' + commit[:message],
      groups: ['internal+'],
      api_token: "ENV['CRASHLYTICS_TOKEN']",
      build_secret: "ENV['CRASHLYTICS_SECRET']"
    )

    if ENV['S3_ACCESS_KEY'] && ENV['S3_SECRET_ACCESS_KEY']

      bundle_version = get_info_plist_value(path: 'Info.plist', key: 'CFBundleShortVersionString')

      s3_url = upload_s3_file(file: '../Runkeeper.ipa',
      access_key: ENV['S3_ACCESS_KEY'],
      secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
      bucket: '',
      path: 'builds/mobile/iPhone/internal/' + bundle_version,
      s3_file_name: 'Runkeeper.ipa')

      postToSlack("iOS Internal build created", s3_url, "iOS S3 Build")
    else
      postToSlack("iOS Internal build created")
    end
  end

  after_all do |lane|
    print lane
    if lane == "test"
      postTestResultsToSlack()
    end
  end

  error do |lane, exception|
      slack(
        message: "The build failed... (╯°□°)╯︵ ┻━┻", exception.message,
        success: false
        )
  end

#Custom functions
#------------------------------------------------------------------------------------
  # Adds build information to plist to display in app

############################# UTIL ##############################

  private_lane :build do |options|
    setupBuildInfo()
    scheme = options[:scheme]

    gym(
      scheme: scheme, 
      clean: true, 
      include_bitcode: false,
      workspace: "RunKeeper.xcworkspace",
      output_directory: "../",
      output_name: "Runkeeper.ipa",
      xcargs: "ARCHIVE=YES" # Used to tell the Fabric run script to upload dSYM file
    )
  end

  def setupBuildInfo()

    print "Setting up build info"    
    set_info_plist_value(
      path: "Info.plist",
      key: "fl_commit_message",
      value: last_git_commit[:message]
    )
  
    print "fl_commit_message = " + last_git_commit[:message]

    set_info_plist_value(
      path: "Info.plist",
      key: "fl_branch",
      value: git_branch
    )

    print "fl_branch = " + git_branch

    commit = `git rev-parse HEAD`
    commit = commit.gsub('\n', '')
    commit = commit.gsub('\t', '')

    set_info_plist_value(
      path: "Info.plist",
      key: "fl_commit_hash",
      value: commit
    )

    print "fl_commit_hash = " + commit

    time = Time.now.strftime("%m/%d/%Y %H:%M")

    set_info_plist_value(
      path: "Info.plist",
      key: "fl_build_time",
      value: time
    )

    print "fl_build_time = " + time

    if ENV["BITRISE_BUILD_NUMBER"]
      set_info_plist_value(
      path: "Info.plist",
      key: "fl_bit_rise_build_number",
      value: ENV["BITRISE_BUILD_NUMBER"]
    )
    end

  end

  #To be run by CI machine based on lane needed
  lane :matchSetup do |options|
    type = options[:type]
    match(app_identifier: "RunKeeperPro", readonly: true, type: type)
    match(app_identifier: "RunKeeperPro.watchapp", readonly: true, type: type)
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: true, type: type)
  end

  #To be run whenever profiles change
  lane :downloadProfiles do |options|    
    match(app_identifier: "RunKeeperPro", readonly: true, type: "development")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: true, type: "development")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: true, type: "development")
    match(app_identifier: "RunKeeperPro", readonly: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro", readonly: true, type: "appstore")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: true, type: "appstore")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: true, type: "appstore")
  end

  #To be run whenever new devices have been added. Only a few people have access to the repository to run this
  lane :updateProfiles do |options|    
    match(app_identifier: "RunKeeperPro", readonly: false, force: true, type: "development")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: false, force: true, type: "development")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: false, force: true, type: "development")
    match(app_identifier: "RunKeeperPro", readonly: false, force: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: false, force: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: false, force: true, type: "adhoc")
    match(app_identifier: "RunKeeperPro", readonly: false, force: true, type: "appstore")
    match(app_identifier: "RunKeeperPro.watchapp", readonly: false, force: true, type: "appstore")
    match(app_identifier: "RunKeeperPro.watchapp.watchextension", readonly: false, force: true, type: "appstore")
  end

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

    if ENV["SLACK_URL"]
      if s3_url != nil && url_title != nil
        slack(
          message: message,
          success: true,
          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: message,
          success: true,
          default_payloads: [:test_result, :git_branch]       
        )
      end
    end
  end

  def postTestResultsToSlack()
    if ENV['S3_ACCESS_KEY'] && ENV['S3_SECRET_ACCESS_KEY']
      s3_url = upload_s3_file(file: 'fastlane/test_output/report.html',
        access_key: ENV['S3_ACCESS_KEY'],
        secret_access_key: ENV['S3_SECRET_ACCESS_KEY'],
        bucket: '',
        path: 'builds/mobile/iPhone/tests/' + bundle_version,
        s3_file_name: 'report.html')
      postToSlack("iOS Test Results", s3_url, "Test Results")
    else
      postToSlack(file: 'fastlane/test_output/report.html')
    end
  



  end




