//go:build ignore
//+build ignore

package main

import (
	"fmt"
	"log"
	"net/http"
	"strconv"
	"strings"

	. "github.com/dave/jennifer/jen"
)

const maxPodsPerNodeTypeSourceText = "https://raw.github.com/awslabs/amazon-eks-ami/master/files/eni-max-pods.txt"

func main() {
	fmt.Println("Generating maxpods.go file...")
	maxPodsMap := generateMap()
	renderGoMap(maxPodsMap)
}

func generateMap() map[string]int {
	dict := make(map[string]int)

	resp, err := http.Get(maxPodsPerNodeTypeSourceText)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err.Error())
	}

	for _, line := range strings.Split(string(body), "\n") {
		if strings.HasPrefix(line, "#") {
			continue
		}
		parts := strings.Split(line, " ")
		if len(parts) != 2 {
			continue
		}
		instanceType := parts[0]
		maxPods, err := strconv.Atoi(parts[1])
		if err != nil {
			log.Fatal(err.Error())
		}
		dict[instanceType] = maxPods
	}

	return dict
}

func renderGoMap(maxPodsMap map[string]int) {
	f := NewFile("nodebootstrap")

	f.Comment("This file was generated by maxpods_generate.go; DO NOT EDIT.")
	f.Line()
	f.Comment("Source: " + maxPodsPerNodeTypeSourceText)

	dict := Dict{}
	for k, v := range maxPodsMap {
		dict[Lit(k)] = Lit(v)
	}

	f.Var().Id("maxPodsPerNodeType").Op("=").
		Map(String()).Int().Values(dict)

	if err := f.Save("maxpods.go"); err != nil {
		log.Fatal(err.Error())
	}
}
