platform :android do
 lane :pspnBuildAndroid do |options|
   pspnSlackMessage("Starting PSPN build for #{$globalGameName} android")

   begin
     sh("rm -f ../app/build/outputs/apk/debug/#{$globalBuildPrefix}*")
   rescue => ex
   end

   if options[:clean]
    begin
      gradle(
        task: 'clean'
      )
    rescue => ex
      begin
        gradle(
          task: 'clean'
        )
     rescue => ex
       pspnOnError(ex)
       return
     end
    end
   end

   begin
     gradle(
       task: 'assemble',
       build_type: 'Debug'
     )
   rescue => ex
     begin
       gradle(
       task: 'assemble',
       build_type: 'Debug'
     )
    rescue => ex
      pspnOnError(ex)
      return
    end
   end

   begin
     pspnBuildLink = "https://little-engine.com/builds/pspn/#{$globalGameName}/android"
     pspnLittleEnginePath = "/home/ubuntu/builds/pspn/#{$globalGameName}/android"
     x = sh("ls ../app/build/outputs/apk/debug/#{$globalBuildPrefix}*")
     x = x.gsub("\n","")
     y = x.split('/',-1)[-1]
     sh("scp #{x} aws2:#{pspnLittleEnginePath}")
     pspnPurgeCache("#{pspnBuildLink}/#{y}")
     sleep 30
     pspnSlackMessage("#{$globalGameName} android build uploaded - #{pspnBuildLink}/#{y}")
   rescue => ex
     pspnOnError(ex)
     return
   end
 end
end

platform :ios do
 lane :pspnBuildIos do |options|
   pspnSlackMessage("Starting PSPN build for #{$globalGameName} iOS")

   begin
     sh("rm -rf ../pspn_generated/#{$globalBuildPrefix}*")
   rescue => ex
   end

   begin
     increment_version_number(
       version_number: options[:version]
     )
     increment_build_number(
       build_number: options[:build_number]
     )
   rescue => ex
     pspnOnError(ex)
     return
   end

   begin
     unlock_keychain(path: "PSFastlane", password: "WhereBe1heCert*")
     match(git_branch: "ps_ios_certs", username: "ios-certificates@playsimple.in", readonly: true, type: "development", keychain_name: "PSFastlane")
     version_number = get_version_number()
     build_app(scheme: "#{$globalXcodeScheme}", workspace: "#{$globalXcodeWorkspace}", output_name: "#{$globalBuildPrefix}-#{version_number}.ipa", output_directory: "./pspn_generated/#{$globalBuildPrefix}-#{version_number}", export_method: "development", clean: options[:clean])
   rescue => ex
     pspnOnError(ex)
     return
   end

   begin
     pspn_manifest_url = "https://little-engine.com/share/pspn/%GAME_DIRECTORY%/%BUILD_NAME%/manifest.plist"
     pspn_build_url = "https://little-engine.com/share/pspn/%GAME_DIRECTORY%/%BUILD_NAME%/%BUILD_NAME%.ipa"

     build_name = "#{$globalBuildPrefix}-#{version_number}"
     build_dir = File.join("..", "pspn_generated", build_name)

     pspn_manifest_url.gsub!("%GAME_DIRECTORY%", $globalGameName);
     pspn_manifest_url.gsub!("%BUILD_NAME%", build_name);

     pspn_build_url.gsub!("%GAME_DIRECTORY%", $globalGameName);
     pspn_build_url.gsub!("%BUILD_NAME%", build_name);

     html_read_path = File.join(File.dirname(__FILE__), "../../../frameworks/runtime-src/proj.ios_mac/fastlane/manifest.html.tpl")
     html_template_data = File.read(html_read_path)
     html_template_data.gsub!("%MANIFEST_URL%", pspn_manifest_url)
     html_template_data.gsub!("%BUILD_DIRECTORY%", build_name)
     html_write_path = File.join("..", "pspn_generated", "#{build_name}.html")
     File.write(html_write_path, html_template_data)
     sh("scp #{html_write_path} aws2:/home/ubuntu/builds/pspn/#{$globalGameName}/ios/#{build_name}.html")

     manifest_read_path = File.join(File.dirname(__FILE__), "../../../frameworks/runtime-src/proj.ios_mac/fastlane/manifest.plist.tpl")
     plist_template_data = File.read(manifest_read_path)
     plist_template_data.gsub!("%BUILD_URL%", pspn_build_url)
     plist_template_data.gsub!("%BUILD_NUMBER%", version_number)
     plist_template_data.gsub!("%GAME_ID%", $globalGameId)
     plist_template_data.gsub!("%GAME_PACKAGE_ID%", $globalIosPackage)
     plist_template_data.gsub!("%GAME_STORE_NAME%", $globalIosStoreName)
     plist_write_path = File.join(build_dir, "manifest.plist")
     File.write(plist_write_path, plist_template_data)
     sh("rm -f #{build_dir}/#{build_name}.app.dSYM.zip")
     sh("scp -r #{build_dir} aws2:/var/www/legames/share/pspn/#{$globalGameName}/")
     pspnSlackMessage("#{$globalGameName} iOS build uploaded - https://little-engine.com/builds/pspn/#{$globalGameName}/ios/#{build_name}.html")
   rescue => ex
     pspnOnError(ex)
     return
   end
 end
end

def pspnOnError(exception)
  puts "Error occurred: #{exception}"
  slack(
   message: "Error occurred!",
   success: false,
   slack_url: "https://hooks.slack.com/services/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",
   attachment_properties: {
     fields: [
       {
         title: "Error message",
         value: exception
       }
     ]
   }
 )
end

def pspnSlackMessage(msg)
  slack(
    message: msg,
    success: true,
    slack_url: "https://hooks.slack.com/services/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"
  )
end

def pspnPurgeCache(file)
 require 'net/http'
 require 'uri'
 require 'json'
 cf_api = ENV["CLOUDFLARE_PURGE_CACHE_API"]
 cf_key = ENV["CLOUDFLARE_PURGE_CACHE_KEY"]
 uri = URI.parse(cf_api)
 request = Net::HTTP::Post.new(uri)
 request.content_type = "application/json"
 request["Authorization"] = "Bearer #{cf_key}"
 request.body = JSON.dump({
   "files" => [
     file
   ]
 })

 req_options = {
   use_ssl: uri.scheme == "https",
 }

 response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
   http.request(request)
 end
 x = JSON.parse(response.body)
 y = x["success"]

 if y
   puts "Cache purged sucessfully."
 else
   puts "Cache not purged."
   pspnOnError("Build uploaded but cache not purged. Response from cloudflare API - #{x}")
   raise "An error occurred."
 end
end
