#!/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'] == 'a-2-c-override'

DO_NOT_MESS_UP_THIS_DOMAIN = 'XYZ.twitch.tv'

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']

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

# get existing records
puts "Getting records for #{DO_NOT_MESS_UP_THIS_DOMAIN}"
begin
  res = RestClient.get("https://oauth:#{TWITCH_OAUTH_TOKEN}@#{DNS_API}?name=#{DO_NOT_MESS_UP_THIS_DOMAIN}&type=#{OLD_RECORD_TYPE}")
rescue RestClient::ExceptionWithResponse => e
  abort "GET - Invalid response code #{e.response.status} - #{e.response.body}"
end
current_records = JSON.parse(res.body)

# delete old records
puts "Deleting previous records for #{DO_NOT_MESS_UP_THIS_DOMAIN}"
current_records.each do |record|
  puts "Deleting #{record['id']}"
  begin
    res = RestClient::Request.execute(method: 'delete', url: "https://oauth:#{TWITCH_OAUTH_TOKEN}@#{DNS_API}", payload: record.to_json)
  rescue RestClient::ExceptionWithResponse => e
    abort "DELETE - Invalid response code #{e.response.status} - #{e.response.body}"
  end
end

# create new records
puts "Creating Fastly CNAME records for #{DO_NOT_MESS_UP_THIS_DOMAIN}"
VIEWS.each do |v|
  puts "Creating #{v} record - #{FASTLY_MAP}"
  record = { name: DO_NOT_MESS_UP_THIS_DOMAIN, ttl: 60, view: v, type: 'cname', target: FASTLY_MAP }
  begin
    res = RestClient.post("https://oauth:#{TWITCH_OAUTH_TOKEN}@#{DNS_API}", record.to_json)
  rescue RestClient::ExceptionWithResponse => e
    abort "POST - Invalid response code #{e.response.status} - #{e.response.body}"
  end
end
