#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'aws-sdk-s3'
require 'aws-sdk-lambda'
require 'zip'

def fetch(uri_str, limit = 10)
    # You should choose a better exception.
    raise ArgumentError, 'too many HTTP redirects' if limit == 0

    response = Net::HTTP.get_response(URI(uri_str))

    case response
    when Net::HTTPSuccess then
        response
    when Net::HTTPRedirection then
        location = response['location']
        warn "redirected to #{location}"
        fetch(location, limit - 1)
    else
        response.value
    end
end

def lambda_handler(event:, context:)
    response = fetch("https://docs.google.com/spreadsheets/d/1DHEsiv4cY4gE6AX3sVH82K__mpBD1aznIYCQwQxA_F0/export?gid=0&format=tsv")

    stringio = Zip::OutputStream.write_buffer do |zio|
        zip_entry = Zip::Entry.new(zio, 'names.tsv', nil, nil, nil, nil, nil, nil, Zip::DOSTime.at(0))
        zio.put_next_entry(zip_entry)
        zio.write(response.body)
    end
    stringio.rewind
    new_contents = stringio.string.bytes

    s3 = Aws::S3::Client.new
    original_resp = s3.get_object(bucket:'eagle0', key:'names.tsv.zip')
    original_contents = original_resp.body.string.bytes

    if original_contents != new_contents then
        puts "Different contents"
        resp = s3.put_object(body: stringio.sysread, bucket:'eagle0', key:'names.tsv.zip')
        puts "successfully uploaded zip"
        puts resp

        client = Aws::Lambda::Client.new
        lambda_response = client.publish_layer_version({
            layer_name: "namesLayer",
            content: {
                s3_bucket: 'eagle0',
                s3_key: 'names.tsv.zip'
            }
        })
        new_version_arn = lambda_response.layer_version_arn
        puts "successfully updated layer"
        puts lambda_response

        lambda_response = client.update_function_configuration({
            function_name: "Name_Generator",
            layers: [new_version_arn, "arn:aws:lambda:us-east-1:339296677100:layer:nameConstructionLayer:2"]
        })
        puts "successfully updated config"
        puts lambda_response

        { statusCode: 200, headers: { "Content-Type": "text/html; charset=UTF-8" }, body: lambda_response }
    else
        puts "Contents are identical, not uploading"
        { statusCode: 200, headers: { "Content-Type": "text/html; charset=UTF-8" }, body: "No change" }
    end
end

lambda_handler(event: nil, context: nil)