// Copyright 2017 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

//go:build tools
// +build tools

package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"text/template"
)

const content = `// Code generated by regen.go. DO NOT EDIT.

package stack

import (
	"html/template"
)

const indexHTML = {{.IndexHTML}}

// favicon is the bomb emoji U+1F4A3 in Noto Emoji as a 128x128 base64 encoded
// PNG.
//
// See README.md for license and how to retrieve it.
const favicon template.HTML = "{{.Favicon}}"
`

// loadGoroutines returns "goroutines.tpl" slightly processed for density.
func loadGoroutines() ([]byte, error) {
	htmlRaw, err := ioutil.ReadFile("goroutines.tpl")
	if err != nil {
		return nil, err
	}
	// Strip out leading whitespace.
	re := regexp.MustCompile("(\\n[ \\t]*)+")
	htmlRaw = re.ReplaceAll(htmlRaw, []byte("\n"))
	return htmlRaw, nil
}

func mainImpl() error {
	htmlRaw, err := loadGoroutines()
	if err != nil {
		return err
	}

	// See README.md how to generate it.
	iconRaw, err := ioutil.ReadFile("emoji_u1f4a3_64.gif")
	if err != nil {
		return err
	}

	t, err := template.New("t").Parse(content)
	if err != nil {
		return err
	}
	data := map[string]string{
		"IndexHTML": strconv.Quote(string(htmlRaw)),
		"Favicon":   base64.StdEncoding.EncodeToString(iconRaw),
	}
	b := bytes.Buffer{}
	if err := t.Execute(&b, data); err != nil {
		return err
	}
	return ioutil.WriteFile("data.go", b.Bytes(), 0666)
}

func main() {
	if err := mainImpl(); err != nil {
		fmt.Fprintf(os.Stderr, "Failed: %s\n", err)
		os.Exit(1)
	}
}
