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

require 'rest-client'
require 'json'

abort 'RUN THIS SCRIPT WITH EXTREME CAUTION!' unless ENV['OVERRIDE_SELF_DESTRUCT_SEQUENCE'] == 'multi-a-override'

DNS_API = 'dnsapi.internal.justin.tv/api/v1/record'

# to get your twitch oauth token go here in browser: https://dnsapi.internal.justin.tv/login/oauth2/authorization
TWITCH_OAUTH_TOKEN = ENV['TWITCH_OAUTH_TOKEN']

VIEWS = %w[external internal].freeze
FASTLY_MAP = 'twitch.map.fastly.net'

COUNTRY_DOMAINS = %w[false123].freeze

COUNTRY_DOMAINS.each do |cd|
  # get existing records
  puts "Getting records for #{cd}.twitch.tv"
  begin
    res = RestClient.get("https://oauth:#{TWITCH_OAUTH_TOKEN}@#{DNS_API}?name=#{cd}.twitch.tv&type=cname")
  rescue RestClient::ExceptionWithResponse => e
    abort "GET - Invalid response code #{e.response.code} - #{e.response.body}"
  end
  current_records = JSON.parse(res.body)

  # update old records
  puts "Updating previous records for #{cd}.twitch.tv"
  current_records.each do |record|
    VIEWS.each do |v|
      puts "Updating #{v} record - #{cd}.twitch.tv - #{record['id']}"
      begin
        record['target'] = FASTLY_MAP
        res = RestClient.put("https://oauth:#{TWITCH_OAUTH_TOKEN}@#{DNS_API}", record.to_json)
      rescue RestClient::ExceptionWithResponse => e
        abort "PUT - Invalid response code #{e.response.code} - #{e.response.body}"
      end
    end
  end
end
