#!/usr/bin/env ruby
# frozen_string_literal: true

require 'json'
require 'faraday'

def teamcity_fail(message, details: nil, hard_fail: true)
  puts "####teamcity[buildProblem description='#{message}']"
  if hard_fail
    abort details unless details.nil?
    exit 1
  end
end

def teamcity_success(message, force_exit: false)
  puts "##teamcity[buildStatus status='SUCCESS' text='#{message}']"
  exit if force_exit
end

def teamcity_message(message)
  puts "##teamcity[message text='#{message}']"
end

def teamcity_parameter(key, value)
  puts "##teamcity[setParameter name='#{key}' value='#{value}']"
end

def url_friendly_branch
  BRANCH.tr('_/', '-')
end

BRANCH = ENV['BRANCH'].freeze
DEPLOY_TIMEOUT = (ENV['DEPLOY_TIMEOUT'] || 600).to_i.freeze
GURU_ADDR = ENV['GURU_ADDR'].freeze
GURU_RELEASE_ID = ENV['GURU_RELEASE_ID'].freeze
TWILIGHT_BUILD_ID = ENV['TWILIGHT_BUILD_ID'].freeze

guru = Faraday.new(url: GURU_ADDR)

success = false
message = nil
started_at = Time.now

until success
  break if Time.now > started_at + DEPLOY_TIMEOUT
  sleep 5

  res = guru.get "/release/#{GURU_RELEASE_ID}"

  # good response from Guru?
  unless res.status == 200
    teamcity_message "Guru returned with code #{res.status}"
    next
  end

  data = JSON.parse(res.body)
  case data['status']
  when 0
    teamcity_message 'Guru: Deploy pending...'
  when 1
    teamcity_message 'Guru: Uploading assets...'
  when 2
    teamcity_message 'Guru: Uploading package...'
  when 3
    teamcity_message data['deployStatusMessage']
    break
  when 4
    teamcity_message 'Guru: Finalizing...'
  when 5
    teamcity_message 'Guru: Deploy complete.'
    success = true
  end

  message = data['deployStatusMessage']
end

# do we pass?
unless success
  if Time.now > started_at + DEPLOY_TIMEOUT
    msg = 'Deploy timed out. Check the build log and verify status at https://savant.internal.justin.tv.'
    teamcity_fail msg, details: msg
  else
    teamcity_fail 'Deploy failed. Please check the build log for more details.', details: message
  end
end

# we pass!
if GURU_ADDR.include?('test')
  teamcity_success "Build is available at https://#{url_friendly_branch}.twitch.tech/"
elsif GURU_ADDR.include?('shadow')
  teamcity_success "Build is available at https://#{url_friendly_branch}.rc.twitch-shadow.net/"
else
  teamcity_success "Build is available at https://#{url_friendly_branch}.rc.twitch.tv/"
end

# not perfect, but wait a bit longer until Sage has fully updated its manifest
sleep 15
