//go:build ignore

// Generate quotes.go from quotes.txt, see "go generate" in httpd.go

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

func main() {
	txtFile := os.Getenv("QUOTES_FILE")
	if txtFile == "" {
		txtFile = "quotes.txt"
	}
	file, err := os.Open(txtFile)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	goFile := os.Getenv("GO_FILE")
	if goFile == "" {
		goFile = "quotes.go"
	}

	out, err := os.Create(goFile)
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()

	fmt.Fprintf(out, header)

	hasErr := false
	s := bufio.NewScanner(file)
	var lines []string
	lnum := 0
	for s.Scan() {
		lnum++
		if strings.TrimSpace(s.Text()) == "" {
			if len(lines) > 0 {
				fmt.Fprintf(os.Stderr, "%d: no author\n", lnum)
				hasErr = true
			}
			lines = lines[:0]
			continue
		}

		if strings.HasPrefix(s.Text(), authorPre) {
			author := strings.TrimPrefix(s.Text(), authorPre)
			quote := strings.Join(lines, "\n")
			fmt.Fprintf(out, "{%q, %q},\n", quote, author)
			lines = lines[:0]
			continue
		} else {
			lines = append(lines, s.Text())
		}
	}

	if err := s.Err(); err != nil {
		log.Fatal(err)
	}

	fmt.Fprintf(out, "}\n")

	if len(lines) > 0 {
		fmt.Fprint(os.Stderr, "error: dangling content\n")
		hasErr = true
	}

	if hasErr {
		os.Exit(1)
	}
}

const (
	authorPre = "    - "
	header    = `
// Automatically generated by gen_quotes.go, DO NOT EDIT manually
package main

type Quote struct {
	Content string "json:\"content\""
	Author string  "json:\"author\""
}

var QuoteDB = []Quote {
`
)
