package main

import (
	"flag"
	"io/ioutil"
	"time"

	"bufio"
	"fmt"
	"os"
	"path"
	"strings"

	"golang.org/x/tools/imports"
)

var wordlists = map[string]string{
	"eff_large_wordlist":       "en",
	"eff_short_wordlist_2_0":   "en_eff_short",
	"de_wordlist": "de",
}

var fn = flag.String("o", "xkcdpwgen/generated.go", "Name of the generated file")

func main() {
	flag.Parse()

	src := `// DO NOT EDIT THIS FILE!
//
// Update it by running: go generate
//`

	generatedAt := time.Now().UTC().Format("2006-01-02 15:04:05")

	src += "// Generated at: " + generatedAt + `

package xkcdpwgen

var wordlists = map[string][]string{
`

	for wordlist, varname := range wordlists {

		fullpath := path.Join("wordlists", fmt.Sprintf("%s.txt", wordlist))
		fh, err := os.Open(fullpath)
		if err != nil {
			panic(err)
		}
		defer fh.Close()

		scanner := bufio.NewScanner(fh)
		scanner.Split(bufio.ScanLines)

		src += fmt.Sprintf("    \"%s\": {", varname)

		for scanner.Scan() {
			spl := strings.Fields(scanner.Text())
			if len(spl) == 2 {
				src += fmt.Sprintf("\"%s\",", spl[1])
			}
		}

		src += "},\n"
	}
	src += "}\n"

	res, err := imports.Process(*fn, []byte(src), nil)
	if err != nil {
		panic(err)
	}

	err = ioutil.WriteFile(*fn, res, 0644)
	if err != nil {
		panic(err)
	}
}
