package main

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

const (
	inputFile  = "README.md"
	outputFile = "usage.go"
)

// Convert README.md to a usage function.
func main() {
	inFile, err := os.Open(inputFile)
	if err != nil {
		log.Fatal(err)
	}
	defer inFile.Close()
	scanner := bufio.NewScanner(inFile)

	w := NewWriter(outputFile)
	w.prLn("// Code generated by internal/gen/main.go; DO NOT EDIT.")
	w.prLn("package main")
	w.prLn("")
	w.prLn("")
	w.prLn("const (")
	w.prLn("  usageMsg = `")

	// Skip the first two lines.
	scanner.Scan()
	scanner.Scan()
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.Replace(line, "`", "'", -1)
		line = strings.Replace(line, "\\[", "[", -1)
		line = strings.Replace(line, "\\]", "]", -1)
		w.prLn(line)
	}
	w.prLn("`")
	w.prLn(")")
	w.close()

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

type writer struct {
	f *os.File
}

func NewWriter(n string) *writer {
	f, err := os.Create(n)
	if err != nil {
		log.Fatalf("unable to create `%s`; %v", n, err)
	}
	return &writer{f: f}
}

func (w *writer) prLn(line string) {
	_, err := w.f.WriteString(line + "\n")
	if err != nil {
		log.Printf("Trouble writing: %s", line)
		log.Fatal(err)
	}
}

func (w *writer) close() {
	if err := w.f.Close(); err != nil {
		log.Fatal(err)
	}
}
